9

I was following the below logic to check if a variable is undefined or not:

 if (variable==undefined){
////implementation
}

But found that for some cases it did not function as expected. So, tried this approach,

if(typeof(variable) == "undefined"){
/////implementation
}

So which one is most reliable?

RK-
  • 12,099
  • 23
  • 89
  • 155
  • 1
    see the questions under the Related section on the right side of the page. – Anurag Jun 20 '11 at 05:26
  • possible duplicate of [Detecting an undefined object property in JavaScript](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript) – Asaph Jun 20 '11 at 05:27
  • SO search *javascript undefined check*: 3745 results. – KooiInc Jun 20 '11 at 05:27

2 Answers2

6

Your second way is the most reliable but you don't need the parenthesis for the typeof operator. See this question.

Community
  • 1
  • 1
Asaph
  • 159,146
  • 25
  • 197
  • 199
3
if (variableName){
////implementation
}

this way is more use full than second option

amit kate
  • 120
  • 3