var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Answer from sbeliv01 on Stack OverflowHi, all, I often do stuff like this in my code, to check for a variable being not null and not undefined.
// check if value is not null and not undefined
if (value) {
...
}However, I'm now thinking this can leads to bugs, because of 0, "", false and NaN also being falsy.
What is a better way to check a variable is not null and not undefined? I could use this I think, wondering if there is something shorter than this:
if (typeof value !== 'undefined' || value !== null) {
...
}Videos
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined is true, the above code will catch both null and undefined.
The standard way to catch null and undefined simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.
Edit again
The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.