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.
You can do a strict comparison to the undefined
value.
if (x === undefined) {
x = 0;
}
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 the void
operator to obtain a guaranteed undefined
.You can do a strict comparison to the undefined
value.
if (x === void 0) {
x = 0;
}
The operand to void
doesn't matter. No matter what you give it, it'll return undefined
.
These are all equivalent:
if (x === void undefined) {
x = 0;
}
if (x === void "foobar") {
x = 0;
}
if (x === void x) {
x = 0;
}
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
and undefined
at the same time, and only those value, you can use ==
instead of ===
.
if (x == null) {
x = 0;
}
Now x
will be set to 0
if it was either null
or undefined
, but not any other value. You can use undefined
in the test too. It's exactly the same.
if (x == undefined) {
x = 0;
}
From your question, it seems a little bit like you're specifically looking for number
elements, even NaN
. If you want to limit it to primitive numbers including NaN
, then use typeof
for the test.
if (typeof x !== "number") {
x = 0;
}
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.