How to check if a JavaScript variable is NOT undefined?

Chuck Le Butt picture Chuck Le Butt · Apr 17, 2012 · Viewed 235.1k times · Source

Things I’ve tried that don’t seem to work:

if(lastName != "undefined")
if(lastName != undefined)
if(undefined != lastName)

Answer

sbeliv01 picture sbeliv01 · Apr 17, 2012
var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
}