1

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); 
}

Fiddle

asked Sep 26, 2015 at 14:45
3
  • typeof some_var !== 'undefined' as typeof something gives a string value Commented Sep 26, 2015 at 14:46
  • 1
    Why do you need typeof for that? Why not some_var !== undefined? Commented Sep 26, 2015 at 14:48
  • @MinusFour, that's what I used in the first place, but the result was not as expected. So I then used typeof. I have used undefined so many times before, but @Tushar's explanation of strict inequality taught me a valuable lesson. Commented Sep 26, 2015 at 15:33

1 Answer 1

2

typeof always returns string.

As you're using strict inequality, the condition evaluates to true.

You can either

  1. use undefined as string
  2. use != for inequality

Updated Fiddle

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for a great explanation.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.