Javascript Check Undefined Example
By now we all know that in Javascript we attach types to values and not variables, like in most other programming languages. One of these types is undefined.
All variable declarations are initialized firstly with undefined, until we give them another value. When we don’t declare the variables, they just do not exist, but when we declare them and forget to initialize them?
What about when you have forgotten if you did so, but don’t have the time to go back and search if you initialized it or not? Let’s check!
Strict Equality Operator
When we want to determine whether a variable has a value or not, we use the strict equality operator. We don’t use the equality operator ==
because it also checks true for null
, which is not the same as undefined, although frequently confused.
The code would be like below:
var a; if (a === undefined) { // execute this code } else { // execute this code }
In the case above, since we haven’t initialized the a
variable, the if statement will be true, so the code in the if
clause will be executed.
However, when the variable a
is not even declared before, this method will leave us with a ReferenceError
.
TypeOf Operator
To get rid of the issue we mentioned before about the strict equality operator throwing a ReferenceError
we use the typeOf
operator, as in the code snippet below:
if (typeof a === 'undefined') { // true if a is not declared // execute this code }
However, this does not work for objects. In that case you would have to use it together with in
, this way:
key in yourObject && typeof yourObject.key === 'undefined';
Which alternatively would be like below, if you’re not familiar with the in
operator:
yourObject.hasOwnProperty(key) && typeof yourObject.key === 'undefined';
This way you can easily understand what in
does; namely, returns true if an object has a particular property and false if it doesn’t. Which means that by using this method, we firstly check if the property exists, avoiding the possibility that we get a ReferenceError
, and then check the type of that variable.
Void Operator
As an alternative to undefined
we might use the void
operator like below:
var a; if (a === void 0) { // execute this code }
Note that in this case we have only substituted undefined
for void 0
, and everything else stays the same. That means that, even while using this method, when the variable is not declared, we have a ReferenceError
in our hands.
Whichever method you use, you will be able to check if your variable is undefined or not with efficiency.
Download the source code
This was an example of check undefined in Javascript.
Download the source code for this tutorial:
You can download the full source code of this example here : CheckUndefined