The difference between undefined and undeclared variables in JavaScript is:
- Undefined variable means a variable has been declared but it does not have a value.
- Undeclared variable means that the variable does not exist in the program at all.
Examples
Undefined Variable
To see an example of an undefined value, declare a variable but do not assign it a value:
var dog; console.log(dog);
Output:
Undefined
Undeclared Variable
An example of an undeclared variable is when there is no such variable in the program:
console.log(cat);
Output:
ReferenceError: cat is not defined
How to Check If a Variable Is Undefined in JavaScript
To check if a variable is undefined in JavaScript, use a direct check using the triple equals operator:
someVar === undefined
How to Check If a Variable Is Undeclared in JavaScript
If you try to access an undeclared variable in JavaScript, you get a ReferenceError. This is consistent because if there is no such variable, you cannot use it.
Does this mean you need to do error handling to check if a variable exists in a program?
Nope.
The typeof operator is a great help in this case.
To check if a variable exists in the program, use the typeof operator. It does not throw a ReferenceError with an undeclared variable. Instead, it returns ‘undefined’.
For instance, let’s check if a non-existent variable cat is found:
if(typeof cat === "undefined") { console.log("Cat does not exist in the program"); }
Output:
Cat does not exist in the program
Conclusion
Today you learned what is the difference between undefined and undeclared in JavaScript.
To recap:
- Undefined means you have created a variable but it does not have a value.
- Undeclared means you do not have that variable at all.
Thanks for reading.
Happy coding!