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?
4 Answers 4
foo.bar = (foo.bar || 0) + 1;
should work.
Comments
ES2020 and the nullish coalescing operator allows to simplify it:
foo.bar = (foo.bar ?? 0) + 1;
5 Comments
Since undefined + 1 is NaN, which is falsy, and undefined is falsy, you have a few options.
Assuming your numbers will never be negative (specifically, -1)
foo.bar = foo.bar + 1 || 1
Or this works for any values of foo.bar, though David's answer is probably a better idea.
foo.bar ? foo.bar++ : foo.bar = 1
Comments
You could use this succinct alternative using the double tilde (~~) as the bitwise NOT operator.
foo.bar = ~~foo.bar + 1;
As @CherryDT helpfully points out:
this will cause undesired results outside of the signed 32-bit integer range (~~30000000000 is -64771072 for example)
2 Comments
~~30000000000 is -64771072 for example).Explore related questions
See similar questions with these tags.
(foo.bar || 0)?