Check if a JavaScript Variable is Undefined
In this tutorial, I will explain to you how you can check if JavaScript Variable is undefined.
Variables in JavaScript
We can declare JavaScript variable using the following four keywords:-
- const
- var
- let
- nothing
Difference between undefined and undeclared variables in JavaScript
Undefined:- undefined variable is one that has declared but doesn’t have assigned a value. Undefined is not a keyword.
Undeclared:- It occurs when we don’t initialize a variable or declare it using var or const keywords. When we use typeof with undeclared variable it will throw an error with return value as ‘undefined’.
Now to check whether a JavaScript variable is undefined
As here we need to check a variable for undefined:-
JavaScript has a built-in method that is used to check whether a method is defined or undefined.
typeof is a built-in method which check whether a variable is undefined or defined.
typeof doesn’t throw any exception if we declare an undefined variable. We can also use typeof in cheking for null.
var s; console.log(typeof s); //print undefined var s1; console.log(s1===undefined); //print true //Since,here the variable s1 don’t have any value but the variable exists.//Here the assigned variables don’t have any value but the variable exisOutput:- var s3=56;; console.log(typeof s3); //print type of the value assigned: i.e, Number
Output
Successfully checked if the variable is defined or undefined.
Therefore typeof is the best way to check whether a variable is defined or not in JavaScript.
Leave a Reply