The use of typeof to determine variable definition

I’ve found recently many people typeof variable === 'undefined' to determine if a variable has been set. It bothered me, so I looked into it.


During the 14 code reviews I did yesterday, one common comment was Do not use typeof to determine if a variable exists. This lead me to wonder, why is it so prevalent? Is it copy pasta, or do people know something I do not?

The case FOR typeof (and I can’t believe I’m saying this)

There is one benefit to using typeof variable === 'undefined' and that is the ability to differentiate between a defined variable (i.e. let a;) vs an undefined variable (i.e. b === undefined, which would fail because b is not declared anywhere). Before the advent of linters, this could have had benefits.

The case(s) AGAINST typeof

It’s extremely strange to use it in an if statement when determining whether or not the object exists. For instance:

My opinion

I’m in the “use a !myVariable statement" camp. Not only is it more readable, it's more maintainable and covers a broader case that typically suits the problem trying to be solved by the use of typeof variable === 'undefined' operation. I believe that it had a reason to exist in the past; but with modern linters, its only benefit that I was able to find is a moot one at this point.

Front End Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store