259

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

if(lastName != "undefined")
if(lastName != undefined)
if(undefined != lastName)
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
  • 7
    `if(lastName != undefined)` This didn't work? Are you getting a *ReferenceError* in the console? If so, instead of avoiding the error by using `typeof` *(as Crockford followers will suggest)*, you should be declaring your variables properly. –  Apr 17 '12 at 13:59
  • 4
    if "if(typeof lastName !== "undefined")" is not working for you, you may want to check your code for other problems – joelmdev Apr 17 '12 at 14:02
  • 1
    Any of the last three will work if you're coding properly. Your issue is elsewhere. –  Apr 17 '12 at 14:06
  • 1
    Why not simply inverse working condition ?? if(!(lastName === undefined)) It is true for null and false for undefined. – Jan Nov 13 '19 at 12:49

1 Answers1

519
var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 
sbeliv01
  • 11,550
  • 2
  • 23
  • 24
  • 5
    Can't we just check it with if(lastname)... https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized?noredirect=1&lq=1 – Jordan Oct 03 '18 at 00:45
  • 22
    @Jordan No - because there are other values `lastname` could take which would also match that condition - e.g. `0`, `null`, `''` (empty string). These are called "falsy" values. – Allan Jardine Nov 09 '18 at 16:25
  • 1
    @almcaffee a falsey value is not the same as undefined – Dale Francis Apr 03 '20 at 00:52
  • 1
    more secure code is: if (lastname && typeof lastname !== "undefined"){ alert("Hi. Variable is defined."); } checking if 'lastname 'and is also not 'undefined' – Naveed Ali Jan 12 '22 at 10:20