3

I have the following code:

let visiblePart = $(this).data('visible-part');

if (visiblePart === undefined)
    visiblePart = 0.5;

I'd like to merge requesting the data-visible-part value with checking for its existence to make the code more compact. Unfortunately, there is no overload of .data() with a defaultValue parameter. How to achieve this?

1

1 Answer 1

4

As the value returned by data() when there is no matching key is undefined you can take advantage of the null coalescing operator (??) to coerce it to a default value, like this:

const defaultValue = 0.5;

$('.foo').on('click', e => {
  let visiblePart = $(e.target).data('visible-part') ?? defaultValue;
  console.log(visiblePart);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<button class="foo">Default value</button> 
<button class="foo" data-visible-part="1.234">Visible: 1.234</button>

Sign up to request clarification or add additional context in comments.

3 Comments

As always, || will also activate on falsy values. For example, if $el.data() returns 0. Which it can, since jQuery can store arbitrary data types when using .data(foo). Unlike using the .attr(`data-${foo}`) which will only change or read the DOM, therefore, only store or retrieve strings (or undefined)
?? is better suited, because it checks for undefined or null instead of falsy values
Thank you both - you're indeed correct. ?? is by far the better approach. I've edited the answer. Time to log off on a Friday afternoon I think :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.