268

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

if(lastName != "undefined")
if(lastName != undefined)
if(undefined != lastName)
4
  • 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. Commented Apr 17, 2012 at 13:59
  • 4
    if "if(typeof lastName !== "undefined")" is not working for you, you may want to check your code for other problems Commented Apr 17, 2012 at 14:02
  • 1
    Any of the last three will work if you're coding properly. Your issue is elsewhere. Commented Apr 17, 2012 at 14:06
  • 1
    Why not simply inverse working condition ?? if(!(lastName === undefined)) It is true for null and false for undefined. Commented Nov 13, 2019 at 12:49

1 Answer 1

535
var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 
Sign up to request clarification or add additional context in comments.

5 Comments

Can't we just check it with if(lastname)... stackoverflow.com/questions/5113374/…
@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.
@almcaffee a falsey value is not the same as undefined
more secure code is: if (lastname && typeof lastname !== "undefined"){ alert("Hi. Variable is defined."); } checking if 'lastname 'and is also not 'undefined'
@NaveedAli no it is not. If lastname is false it wont work. And here we need only undefined

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.