Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Default value for jQuery data() method

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading