Friday, September 28, 2007

JavaScript Gotcha: Check for undefined before null

Do you see anything wrong with this line?

if (a !== null typeof(a) !== 'undefined') {
// Do something with a
}

... Well neither did I - but I've had users complaining of an application just giving them a "white screen" - typical of a JavaScript error to abort everything else. The second time I looked at it I could see what the problem was - I was checking for "a !== null" but a did not yet exist! The correct way to do this is

if(typeof(a) !== 'undefined' && a !== null) {
// Do something with a
}

Note to self: Always check undefined before null!

1 comment:

Anonymous said...

¡Es increible!¿En que contexto puede alguien querer hacer una comprobación sobre una variable que no sabe si está o no está declarada?