August 8, 2014 —John Koster
There are quite a few times when writing JavaScript that we need to check if a variable has been set. Keep in mind that we want to check if a variable has been set, not necessarily what its value is.
We can do that by using this little code snippet:
1if (typeof myVariableName === 'undefined') {2 // The myVariableName is undefined!3}
Notice that undefined
is in quotes. That is because the typeof
operator will return a string. Just a little piece of information for the tool belt. The inverse of this is:
1if (typeof myVariableName !== 'undefined') {2 // The myVariableName is defined. We can do whatever we want with it. Hooray!3}
Do note that this method should be used to check if a variable has been defined. There are other ways to determine if a variable has been assigned to. The easiest way is just to assign the variable a default value when you initialize it, say null
, then explicitly check for the default value to determine if the value has been changed.
∎