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?
>Solution :
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>