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?
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.
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.
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.
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”.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With