What is the correct way to check if an variable exists / is defined in JavaScript? I wrote this example statements. But which method is the best one?
if (myVariable) {
//do something
}
if (myVariable !== null) {
// do something
}
if (typeof(myVariable) !== 'undefined') {
// to something
}
Mostly you can use this simple statement:
if (myVariable) {
//do something
}
It will check for:
This statement covers all cases and its the correct and easiest way to check if an variable exists or holds one of the listed values.
You could also use the explicit check for “undefined” like this:
if (typeof(myVariable) !== 'undefined') {
//do something with "myVariable", its defined and available.
}
The “not null” check:
if (myVariable !== null) {
// do something
}
An short an easy way to check if an variable is defined or is not defined:
if (typeof(aVariable) === "undefined") {
// the variable is undefined
}
I use this logic in the most cases when checking for an undefined variable in JavaScript.