javascriptcastingintegerundefined

Cast undefined to 0


Is there a succinct operation in JavaScript (ES2015) that does this:

x => x === undefined ? 0 : x

I keep running into situations where I want to increment x, but it's initially undefined, so the code becomes:

foo.bar = (foo.bar === undefined ? 0 : foo.bar) + 1;

or

foo.bar = (foo.bar ? foo.bar : 0) + 1;

Is there a less repetitive way of doing this cast?


Solution

  • ES2020 and the nullish coalescing operator allows to simplify it:

    foo.bar = (foo.bar ?? 0) + 1;