00 Votes

JavaScript: Test whether JavaScript variable is defined

Tip by Axuter | 2012-06-01 at 18:22

Sometimes we want to know whether a variable in JavaScript has already been defined before.

This is very easy using the following code:

if (typeof a == 'undefined') {
   alert('Variable "a" is not defined!');
} else {
   alert('Variable "a" is defined!');
}

In the example, we test whether the variable named "a" has been defined or not. For this we simply use the function "typeof", which returns the type of the variable. If the variable is not defined, "typeof" returns "undefined" and we know, that we do not have the variable defined before.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.