I have a variable that gets defined by user input. I want to replace its value only if it's undefined
. But not if it's NaN
. How can I do it?
I tried doing x || 0
but that also replaces NaN
values.
I have a variable that gets defined by user input. I want to replace its value only if it's undefined
. But not if it's NaN
. How can I do it?
I tried doing x || 0
but that also replaces NaN
values.
For ES6 users you can simply do:
x ?? 0
??
is a Nullish coalescing operator:
a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
You can use double tilde (~~) bitwise NOT operator.
var a; // undefined
a = ~~a
console.log(a) // 0
It works as a substitute for (+) which works for undefined too:
var a = "10";
a = ~~a
console.log(a) // 10
You can use a combination of typeof and isNaN functions to achieve your desired behavior. Here's an example:
if (typeof x === "undefined" || isNaN(x)) {
x = defaultValue;
}
This code checks if the value of x is undefined or NaN, and if so, replaces it with a default value. Note that the isNaN function is necessary to avoid replacing NaN values, since NaN is not equal to itself and therefore cannot be compared using the usual equality operators.
Alternatively, you can use the Number.isNaN function, which is a newer and more reliable way to check for NaN values:
if (typeof x === "undefined" || Number.isNaN(x)) {
x = defaultValue;
}
This code behaves the same way as the previous example, but uses the Number.isNaN function instead of isNaN. Note that Number.isNaN is only available in newer JavaScript versions (ES6 and later).
I hope this helps!
You can do a strict comparison to the
undefined
value.Naturally you'll want to be sure that
x
has been properly declared as usual.If you have any sensitivities about the
undefined
value being plagued by really bad code (overwritten with a new value), then you can use thevoid
operator to obtain a guaranteedundefined
.You can do a strict comparison to theundefined
value.The operand to
void
doesn't matter. No matter what you give it, it'll returnundefined
.These are all equivalent:
Ultimately if someone squashed
undefined
locally (it can't be squashed globally anymore), it's better to fix that bad code.If you ever want to check for both
null
andundefined
at the same time, and only those value, you can use==
instead of===
.Now
x
will be set to0
if it was eithernull
orundefined
, but not any other value. You can useundefined
in the test too. It's exactly the same.From your question, it seems a little bit like you're specifically looking for
number
elements, evenNaN
. If you want to limit it to primitive numbers includingNaN
, then usetypeof
for the test.However, you'll lose numeric strings and other values that can successfully be converted to a number, so it depends on what you ultimately need.