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-
  • 11,865
  • 22
  • 88
  • 153
  • 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
  • 154,284
  • 25
  • 189
  • 193
3
if (variableName){
////implementation
}

this way is more use full than second option

amit kate
  • 114
  • 3