← Back tothis vs that

variable === undefined vs typeof variable === "undefined"

Written byPhuoc Nguyen
07 Aug, 2020
There are two common ways to check whether a variable is `undefined`. We can use the identical (`===`) or `typeof` operator:
variable === undefined;
typeof variable === 'undefined';


The `typeof` operator works with undeclared variables, while the identical operator will throw a ReferenceError exception.
typeof undeclaredVar === 'undefined'; // true
undeclaredVar === undefined; // throws a ReferenceError exception

Good to know

In the old browsers running ES3 enginee, `undefined` is a global variable name whose primitive value is undefined. The value can be changed:
// ES3
var person = {};
person.name === undefined; // true

// Let's modify the value of undefined
undefined = 'Foo';
person.name === undefined; // false
In order to avoid the issue where `undefined` can be renamed or modified the value, we can wrap the code in an IFFE (immediately invoked function expression) as following:
// It's safe to use undefined here

// Or
In the sample code above, `undefined` is a parameter of function. Since we don't pass any parameter or an undefined variable (`_`) to the function, the parameter will be undefined. This common pattern was used in popular libraries such as jQuery, Backbone, etc.
It's not the case in modern browsers nowadays. From ES5, `undefined` can't be changed because its `Writable` property is set to `false`.

Good practice

Always use `typeof`.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn