Sometimes when we write a javascript program, we received an output of undefined or ReferenceError and we get confused as to what might be going on in our program. Well, worry less, this article is going to simplify it all.
Undefined and Undeclared are two different variables in javascript:
- Undefined variable means a variable has been declared but does not have a value.
- Undeclared variable is insinuating that a variable does not exist in the program at all.
The best way to understand the difference between undefined and undeclared variables in javascript is by having a look at practical examples. So, open your browser console and let's code:
Undefined Variable
To see an example of an undefined value, declare a variable but do not attribute to it any value:
let mySchoolFess;
console.log(mySchoolFees); //Output is Undefined
This is what is meant by an undefined variable in JavaScript. It’s been declared but doesn’t hold value.
Undeclared Variable
An example of an undeclared variable is when there is no such variable in the program, let's try to output a variable called "stockPrice" without having such a variable in the program:
console.log(stockPrice);
Output:
ReferenceError: stockPrice is not defined
How to Check If a Variable Is Undefined or Undeclared in JavaScript
To check if a variable is undefined in JavaScript, use a direct check using the triple equals operator (===):
mySchoolFees === undefined
The above code will check if "mySchoolFees" is defined or not. The console will throw an error if it is not defined and otherwise if there is a value assigned to it.
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.
But does this mean you need to do error handling to check if a variable exists in a program? Nah!
The "typeof operator" is the key player in this case. To check if a variable exists in your program, use the "typeof operator". It does not throw a ReferenceError with an undeclared variable. Instead, it returns ‘undefined’. Tricky, right?
For example, let’s check if a non-existent variable "stockPrice" is found:
if (typeof stockPrice === "undefined") {
console.log("stockPrice isn't initialized");
}
Output:
stockPrice isn't initialized
Undefined and Undeclared are just as simple as the aforementioned explanation and examples cited.
Thanks for going through the articles, if you love it, like-comment your view-follow for more articles. Thanks!