Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice of checking if variable is undefined

I was having some issues in my conditions concerning undefined variables. What is, to sum it up, the best way to check if a variable is undefined?

I was mainly struggling with

x === undefined

and

typeof x === 'undefined'
like image 206
DonJuwe Avatar asked Feb 18 '15 12:02

DonJuwe


2 Answers

You can use both ways to check if the value is undefined. However, there are little nuances you need to be aware of.

The first approach uses strict comparison === operator to compare against undefined type:

var x;
// ...

x === undefined; // true

This will work as expected only if the variable is declared but not defined, i.e. has undefined value, meaning that you have var x somewhere in your code, but the it has never been assigned a value. So it's undefined by definition.

But if variable is not declared with var keyword above code will throw reference error:

x === undefined // ReferenceError: x is not defined 

In situations like these, typeof comparison is more reliable:

typeof x == 'undefined' // true

which will work properly in both cases: if variable has never been assigned a value, and if its value is actually undefined.

like image 119
dfsq Avatar answered Sep 28 '22 09:09

dfsq


x === undefined

does not work if variable is not declared. This returns true only if variable is declared but not defined.

Better to use

typeof x === 'undefined'

like image 40
Anurag Peshne Avatar answered Sep 28 '22 09:09

Anurag Peshne