Could someone please explain why the alert is triggered and states that the variable is undefined, when the if test says that it is defined?
var some_var;
if(typeof some_var !== undefined){
alert(some_var);
}
1 Answer 1
typeof always returns string.
As you're using strict inequality, the condition evaluates to true.
You can either
- use
undefinedas string - use
!=for inequality
var some_var;
if (typeof some_var !== 'undefined') {
alert(some_var);
}
As suggested by @MinusFour, you can use
if (some_var !== undefined) {
answered Sep 26, 2015 at 14:47
Tushar
87.4k21 gold badges164 silver badges182 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ally
Thank you for a great explanation.
lang-js
typeof some_var !== 'undefined'as typeof something gives a string valuetypeoffor that? Why notsome_var !== undefined?typeof. I have usedundefinedso many times before, but @Tushar's explanation of strict inequality taught me a valuable lesson.