238

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

if(lastName != "undefined")
if(lastName != undefined)
if(undefined != lastName)
Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
Chuck Le Butt
  • 45,923
  • 58
  • 187
  • 280
  • 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
  • Why not simply inverse working condition ?? if(!(lastName === undefined)) It is true for null and false for undefined. – Tom Nov 13 '19 at 12:49

1 Answers1

465
var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 
sbeliv01
  • 10,810
  • 2
  • 22
  • 24
  • 3
    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
  • 18
    @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
  • thank you "typeof" works for me – Esteban Preciado Jun 04 '21 at 21:22
  • 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