7

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.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
user3312508
  • 907
  • 4
  • 10
  • 25
  • 1
    `typeof x === 'undefined'` – ajp15243 Dec 05 '14 at 16:15
  • Can you show your code please. – putvande Dec 05 '14 at 16:17
  • 1
    Let's see, how would I check if something is undefined? It sounds like I might a statement which tests something! Maybe I could try an `if` statement. But what would the condition be? Maybe it would be an "equality" condition, which, you know, is `===`. So just guessing, but maybe `x === undefined` would work, or to complete the `if` statement, `if (x === undefined)`. There, that wasn't that hard. –  Dec 05 '14 at 16:19
  • 1
    @blgt actually even if he didn't know about strict equality, he could have just done `x == undefined`, hope he knows that, and it would have worked, except for picking up null as well, which would have been a separate problem he could post to SO about. :-) –  Dec 05 '14 at 16:36

6 Answers6

10

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.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Sam
  • 182
  • 2
  • 11
9

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.

six fingered man
  • 2,460
  • 12
  • 15
  • what if I have the variable defined as such: var x = parseFloat(self.y()); In that case x always becomes NaN whether x is undefined or NaN. Is there any way I can check if X is undefined ? – user3312508 Dec 05 '14 at 16:42
  • @user3312508: you'd just use the `if` statement. You're saying that if `x` is not `undefined`, then you want to run the `parseFloat(self.y());` part and assign it to `x`, right? – six fingered man Dec 05 '14 at 16:45
2

You can test using typeof (among other things):

if (typeof x == 'undefined') x = y;

Another approach is to test strict equality against undefined:

if (x === void 0) x = y

In this case we use void 0 as a safety since undefined can actually be redefined.

Semicolon
  • 6,793
  • 2
  • 30
  • 38
  • 1
    *"since `undefined` can actually be redefined."* Not since ES5. – Felix Kling Dec 05 '14 at 16:23
  • 1
    Sure, but as a practical matter, I would hardly recommend confusing someone who doesn't know how to write an if statement to compare something to undefined with arcana such as `void 0` and its relationship to the practically non-existent probability of `undefined` having been redefined, something I have actually never seen once in more than a decade of JS programming. –  Dec 05 '14 at 16:24
  • 1
    @torazaburo: *"...something I have actually never seen once in more than a decade of JS programming"* You and me both. Strikes me as odd that people obsess over the redefining or shadowing of the global `undefined`, but not of any other global. – six fingered man Dec 05 '14 at 16:28
  • 1
    I actually agree, but I included it since it seems to me to have become standard practice in the last few years, at least in a lot of major libraries, and I figured it made more sense to provide the common practice solution than the one I happen to favor. I actually don't do it myself. – Semicolon Dec 05 '14 at 16:37
  • Didn't want it to sound like I thought you were obsessive about it. I think one almost has to include some "guarded" version otherwise someone out there is going to freak out. – six fingered man Dec 05 '14 at 16:39
0

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!

MOHAMED
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 26 '23 at 18:02
-1

You can do this quite quickly with just a

x === undefined && (x = 0);
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 1
    This is poor syntax and will fail most linters. –  Dec 05 '14 at 16:20
  • I accept linters will complain about an unexpected assignment, but I don't see why this is "poor syntax". It makes use of the fact logic operators can short-circuit. – Paul S. Dec 05 '14 at 16:23
  • 1
    Let the minifiers do this kind of rewriting, which most of them will do. For regular human beings, write an if statement as an if statement. –  Dec 05 '14 at 16:25
-1

boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this

var a;//undefined
a = ~~a
console.log(a)//0
LiuHe
  • 7
  • 1