9

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.

4
  • 1
    typeof x === 'undefined' Commented Dec 5, 2014 at 16:15
  • Can you show your code please. Commented Dec 5, 2014 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. Commented Dec 5, 2014 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. :-) Commented Dec 5, 2014 at 16:36

6 Answers 6

14

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.

Sign up to request clarification or add additional context in comments.

Comments

11

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.

2 Comments

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: 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?
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.

5 Comments

"since undefined can actually be redefined." Not since ES5.
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.
@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.
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.
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.
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!

1 Comment

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.
-1

You can do this quite quickly with just a

x === undefined && (x = 0);

3 Comments

This is poor syntax and will fail most linters.
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.
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.
-1

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

2 Comments

Hi, you could edit your answer to describe what the ~~ operator is instead of that repeated text you wrote.
Fixed and added description.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.