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 answer is “both.”
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:
if(typeof myArray !== 'undefined' && myArray.length > 0)
We’re now performing an operation on
myArray to get the type. We then have to do a string comparison and have a string that we have to maintain (granted, these will probably NEVER change, but you never know!).
In addition, it doesn’t cover the case of
myArray having explicitly been declared as
null. Had something set myArray to null (let's say we did a
find operator and it didn't find the right array in a collection of arrays), this would fail because it would attempt to access the length property on a
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.