inorganik
inorganik

Reputation: 25525

JS: check existence of a var that equals 0

I have a piece of code that tests for the existence of a variable, using an if statement like the example below. I need to do one thing if the var is set, a different thing if its not. In a certain test case, the var needed to be set to 0, but that is the same is having an unset var in JS, apparently:

var toMatch;
toMatch = 0;
if (!toMatch) {
    document.write("no");
} else {
    document.write(toMatch);
}

// html is "no"

jsFiddle

So my problem is, how do I test for a var if its value is legitimately zero. I should point out, that in my function possible values to be passed are 0-40+.

In the past I've used a work around like setting the initial value to a number high enough that it is not likely to be passed to the function but that seems hackey to me. Is there a better way to do it?

Upvotes: 39

Views: 114739

Answers (4)

Sophie Alpert
Sophie Alpert

Reputation: 143134

Instead of

if (toMatch)

use

if (toMatch == null)

Upvotes: 12

Ned Batchelder
Ned Batchelder

Reputation: 375584

You can see if a name is undefined with:

if (typeof bad_name === "undefined") {

Upvotes: 2

Oded
Oded

Reputation: 499002

Javascript is a bit funny when it comes to values and boolean checks. I suggest reading about Truthy and Falsey in Javascript.

You should use the identity inequality operator !==:

var toMatch;
toMatch = 0;
if (toMatch !== 0) {
    document.write("no");
} else {
    document.write(toMatch);
}

It is also worth understanding the differences between == and ===.

Upvotes: 0

Simon Sarris
Simon Sarris

Reputation: 63812

var toMatch;
toMatch = 0;
if (toMatch === 0) { // or !== if you're checking for not zero
    document.write("no");
} else {
    document.write(toMatch);
}

toMatch === 0 will check for zero.

toMatch === undefined will check for undefined

the triple equals are strict comparison operators for this sort of scenario. See this blessed question: Difference between == and === in JavaScript

Upvotes: 47

Related Questions