Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: check existence of a var that equals 0

Tags:

javascript

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?

like image 953
inorganik Avatar asked Feb 07 '12 20:02

inorganik


People also ask

How do you check if a value exists in a variable?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

How do you check if a variable is empty in JS?

Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

How do you check if a variable is defined in JS?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a VAR is a number?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.


1 Answers

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

like image 151
Simon Sarris Avatar answered Oct 12 '22 10:10

Simon Sarris