Problem
I needed to know if the variable was defined or not. The following, for example, results in a not-defined error.
alert( x );
What is the best way for me to catch this error?
Asked by Jineesh
Solution #1
Null is an object in JavaScript. There’s an undefined value for items that don’t exist. The DOM returns null in almost all circumstances where it can’t detect a structure in the document, whereas undefined is the value used in JavaScript.
Second, no, there isn’t an exact match. If you absolutely want to check for null, follow these steps:
if (yourvar === null) // Does not execute if yourvar is `undefined`
Try/catch is the only way to check if a variable exists, because typeof treats an undeclared variable and a variable declared with the value undefined as identical.
However, to see if a variable is declared and not undefined, type:
if (yourvar !== undefined) // Any scope
Because undefined may be reassigned like a variable, it was previously required to use the typeof operator to check for it safely. The former method was as follows:
if (typeof yourvar !== 'undefined') // Any scope
In ECMAScript 5, which was released in 2009, the issue of undefined being re-assignable was resolved. Because undefined has been read-only for some time, you may now safely use === and!== to test for it without requiring typeof.
If you just want to know if a member exists but don’t care about its value, use this formula:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
If you want to know if a variable is true or not, use the following formula:
if (yourvar)
Source
Answered by Natrium
Solution #2
The following is the only technique to genuinely test if a variable is undefined. Remember that in JavaScript, undefined is an object.
if (typeof someVar === 'undefined') {
// Your variable is undefined
}
Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).
Answered by Michael Wales
Solution #3
Technically, I believe the correct solution is:
typeof x === "undefined"
It’s easy to become complacent and rely on shortcuts.
x == null
However, an undefined variable x, as well as a variable x containing null, can both yield true.
Answered by Jason S
Solution #4
A simpler and more condensed version would be:
if (!x) {
//Undefined
}
OR
if (typeof x !== "undefined") {
//Do something since x is defined.
}
Answered by Dmitri Farkov
Solution #5
I’ve often done:
function doSomething(variable)
{
var undef;
if(variable === undef)
{
alert('Hey moron, define this bad boy.');
}
}
Answered by Joe
Post is based on https://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript