0

I am using the following shorthand conditional in JS/jQuery:

var delay = $(this).data("delay") ? $(this).data("delay") : options.delay;

If the element has a data-delay attribute use that value, otherwise get the value from options.delay.

It seems excessive using $(this).data("delay") two times in the shorthand conditional. Is there a better way to do it?

Would var delay = $(this).data("delay") || options.delay; be a good solution? I am not sure if all browser supports it.

3
  • You can use truthy || options.prop Commented Feb 2, 2022 at 7:52
  • "I am not sure if all browser supports it." only every browser which supports JavaScript. I think it's safe to say you shouldn't care about the rest.
    – VLAZ
    Commented Feb 2, 2022 at 7:56
  • Any of those wouldn't work as expected, if delay can be zero. Go with nullish coalescing operator as Svinjica has answered, or If you're worried about browser support, use an if..else instead, don't minify the developement code, a minifier will minify the production code.
    – Teemu
    Commented Feb 2, 2022 at 7:57

1 Answer 1

2

yes, you can use Nullish Coalescing Operator. A nullish value is a value that is either null or undefined.

So, you can use something like this:

var delay = $(this).data("delay") ?? options.delay;

You can read more about it on this page: https://www.javascripttutorial.net/es-next/javascript-nullish-coalescing-operator/

2
  • Thanks! It looks like it has good browser support.
    – CyberJ
    Commented Feb 2, 2022 at 7:57
  • Great, if the answer suits your need then you can accept it to mark it as resolved :)
    – Svinjica
    Commented Feb 2, 2022 at 7:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.