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?
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?
Share Improve this question asked Jun 20, 2011 at 5:22 RK-RK- 12.2k23 gold badges93 silver badges157 bronze badges 3- 1 see the questions under the Related section on the right side of the page. – Anurag Commented Jun 20, 2011 at 5:26
- possible duplicate of Detecting an undefined object property in JavaScript – Asaph Commented Jun 20, 2011 at 5:27
- SO search javascript undefined check: 3745 results. – KooiInc Commented Jun 20, 2011 at 5:27
2 Answers
Reset to default 6Your second way is the most reliable but you don't need the parenthesis for the typeof
operator. See this question.
if (variableName){
////implementation
}
this way is more use full than second option