I know that I can test for a javascript variable and then define it if it is undefined, but is there not some way of saying
var setVariable = localStorage.getItem('value') || 0;
seems like a much clearer way, and I'm pretty sure I've seen this in other languages.
Ran into this scenario today as well where I didn't want zero to be overwritten for several values. We have a file with some common utility methods for scenarios like this. Here's what I added to handle the scenario and be flexible.
It can then be called with the last two parameters being optional if I want to only set for undefined values or also overwrite null or 0 values. Here's an example of a call to it that will set the ID to -1 if the ID is undefined or null, but wont overwrite a 0 value.
It seems more logical to check
typeof
instead ofundefined
? I assume you expect a number as you set the var to0
when undefined:In this case if
getVariable
is not a number (string, object, whatever), setVariable is set to0
ES2020 Answer
With the Nullish Coalescing Operator, you can set a default value if
value
is null or undefined.However, you should be aware that the nullish coalescing operator does not return the default value for other types of falsy value such as
0
and''
.Do take note that browser support for the operator is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020).
Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match
undefined
but alsonull
,false
,0
,NaN
,""
(but not"0"
).If you want to set to default only if the variable is strictly
undefined
then the safest way is to write:On newer browsers it's actually safe to write:
but be aware that it is possible to subvert this on older browsers where it was permitted to declare a variable named
undefined
that has a defined value, causing the test to fail.The 2018 ES6 answer is:
If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.
It seems to me, that for current javascript implementations,
is a nice way to do this (using object deconstruction).