Search code examples
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

  • foo.bar = (foo.bar || 0) + 1;
    

    should work.