I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error
alert( x );
How can I cat
You can also use the ternary conditional-operator:
var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
I often use the simplest way:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
EDIT:
Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."
Technically, the proper solution is (I believe):
typeof x === "undefined"
You can sometimes get lazy and use
x == null
but that allows both an undefined variable x, and a variable x containing null, to return true.
An even easier and more shorthand version would be:
if (!x) {
//Undefined
}
OR
if (typeof x !== "undefined") {
//Do something since x is defined.
}
I use a small function to verify a variable has been declared, which really cuts down on the amount of clutter in my javascript files. I add a check for the value to make sure that the variable not only exists, but has also been assigned a value. The second condition checks whether the variable has also been instantiated, because if the variable has been defined but not instantiated (see example below), it will still throw an error if you try to reference it's value in your code.
Not instantiated - var my_variable;
Instantiated - var my_variable = "";
function varExists(el) {
if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) {
return true;
} else {
return false;
}
}
You can then use a conditional statement to test that the variable has been both defined AND instantiated like this...
if ( varExists(variable_name) ) { // checks that it DOES exist }
or to test that it hasn't been defined and instantiated use...
if( !varExists(variable_name) ) { // checks that it DOESN'T exist }
Another potential "solution" is to use the window
object. It avoids the reference error problem when in a browser.
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}