JavaScript: Checking If a Variable Is Defined

JavaScript

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 it's value is.

We can do that by using this little code snippet:

if (typeof myVariableName === 'undefined') {
    // The myVariableName is undefined!
}

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:

if (typeof myVariableName !== 'undefined') {
    // The myVariableName is defined. We can do whatever we want with it. Hooray!
}

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.

That's all for this little tip! If you have any questions, comments, or want to say "hi!", leave a comment down below!

Start the Discussion

Leave a comment

Subscribe to our newsletter