Main Tutorials

Check if variable is exists in JavaScript

In some cases, your JavaScript may need to depend on a particular variable to “define” or “exists”, in order to process on the next step.

Note
I don’t recommend to do so, as JavaScript shouldn’t involve any business logic, it should be purely basic validation or UI enhancement, but, many still like to code complex JavaScript, it just make the project very hard to maintain.

The “typeof” is a useful operator to check the variable data type. Here’s a list of values returned by the typeof operator:

  1. “number” – variable is a number.
  2. “string” – variable is a string.
  3. “boolean” – variable is a Boolean.
  4. “object” – variable is an object.
  5. null – variable is null.
  6. “undefined” – variable is not defined.

So, in this case, to check if a variable is exists or defined, use “typeof” operator and check if the returned value is “undefined“.

1. typeof == “undefined”

Full HTML example to demonstrate the use of “typeof” to check if a variable is defined.


<html>
<body>
<h1>JavaScript : typeof example</h1>

<script type="text/javascript">
 var str1 = "mkyong.com";

 if(typeof str1 == 'string'){
	document.write(str1 + " is a string <br/>");
 }
 
 if(typeof str1 == 'undefined'){
	document.write("str1 variable is not exists <br/>");
 }else{
	document.write("str1 variable is exists <br/>");
 }
 
 if(typeof str2 == 'undefined'){
	document.write("str2 variable is not exists <br/>");
 }else{
	document.write("str2 variable is exists <br/>");
 }

</script>

</body>
</html>

2. Demo

Open above HTML file in your web browser, following result will be returned.


mkyong.com is a string 
str1 variable is exists 
str2 variable is not exists 
typeof example

Download Source Code

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Vaibhav Sharma
5 years ago

What if a variable is declared but not defined, for ex:
var foo;
console.log(typeof foo === “undefined”); //true

In this case, foo does exist but has not been initialized which means it stores undefined value. Even its type will be undefined
So I think typeof check won’t be a foolproof idea to check for a variable’s existence.

Robert
6 years ago

Can’t download the source code.When I click on the download button (green arrow on top of plate), nothing happens.

Please help!