Phine Solutions web work notes

Why you should use typeof operator to check whether a variable is defined in Javascript

Filed under: javascript — 1.618 @ 1:12 pm

We often check if a variable is defined or not in javascript before proceeding the next line of code. Usually the code somewhat looks like this:

var myUndefinedVar = 1;

if (myUndefinedVar) {

// do some stuff

}

Even the browser will throw out an Javascript error, the code works since there is no else statement or other intended logics beneath the if block in this case. Otherwise, we won’t be so lucky since the browser will stop executing the rest of the statements. A better way is using the typeof operator, which will not result in an browser error even the variable is undefined. Here is a code example:

if (typeof(myUndefinedVar) == ‘undefined’) {

// do this

} else {

// do that

}

Notice that, the following code will work whether the document element is there or not.

if (document.getElementById(’blah’)) {

}

The reason is that document is always a valid object and getElementById will either return an object or a null value, which in either case, will not cause the browser to throw up.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

©phinesolutions.com