Found this in our code. What's the difference between:
if (typeof isValid === 'undefined') {
and
if (isValid === 'undefined') {
Why would anyone use the first one, I don't understand how this makes sense?
Found this in our code. What's the difference between:
if (typeof isValid === 'undefined') {
and
if (isValid === 'undefined') {
Why would anyone use the first one, I don't understand how this makes sense?
This:
if (typeof isValid === 'undefined') {
checks to see if the type of isValid
is "undefined"
. It could be "undefined"
because either A) isValid
is a variable with the value undefined
in it, or B) It's an undeclared identifier.
This:
if (isValid === 'undefined') {
checks to see if the variable isValid
contains the string "undefined"
. The variable must exist (e.g., be declared), or a ReferenceError
is thrown.
You see the first in situations where the author isn't sure the variable isValid
has been declared, or because they're worried that undefined
may have been redefined in the scope where the code occurs, or because a long time ago they were worried that the undefined
in one realm (loosely: window/tab) and the undefined
in another realm wouldn't be ===
to each other. (If that was ever true, it hasn't been for at least a decade.)
if (typeof isValid === 'undefined') {
means that you want to check if the variable has any value or not, whereas if (isValid === 'undefined') {
means that you want to check if the variable has a string value 'undefined'