0

Let's say you have the following function:

var variable; function(variable); function function(variable) { alert ("variable equals " + variable); if (variable != 'undefined') { ~~~code1~~~ } else { ~~~code2~~~ } } 

The alert outputs:

variable equals undefined

However, ~~~code2~~~ is never executed. I'm guessing that my syntax is incorrect. If I haven't defined the variable, how do I get the function function to execute ~~~code2~~~?

Extra Information

When the variable variable is hardcoded, as in the following code:

var variable; function(variable) function function(variable) { variable = 2; alert ("variable equals " + variable); if (exponent == 2) { ~~~code1~~~ } else { ~~~code2~~~ } } 

~~~code1~~~ is executed.

3
  • 1
    Try doing !== or typeof !== See stackoverflow.com/questions/27509/… Commented Aug 28, 2013 at 1:44
  • 2
    You are alerting a variable called "variable" but your if test is on a variable called "exponent". The way you describe the problem sounds to me like you think you only have the one variable. For the code you've shown it makes no sense that assigning a value of 2 to variable would affect the if test on exponent. Also, please clarify what you mean by "undefined variable", because it could mean "variable that exists but that holds the value undefined" or it could mean "variable that doesn't exist at all". Commented Aug 28, 2013 at 2:06
  • Hmm, it does seem to be a duplicate. I guess my search query was a bit off, but thanks to everyone who replied. Commented Aug 28, 2013 at 2:57

1 Answer 1

3
> exponent != 'undefined' 

You need to understand the Abstract Equality Comparison Algorithm. The above attempts to compare the value of exponent with the string "undefined". Since exponent is defined but has not been assigned a value, it will return the value undefined which is not equal to the string "undefined" (according to the algorithm above).

So you can compare its value to the undefined value:

exponent != undefined 

or you can compare the type of the value with an appropriate string value using the typeof operator (since it always returns a string):

if (typeof exponent != 'undefined') 

Whether you use the strict or abstract versions above (!== or != respectively) doesn't make any difference in this case.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, it seems that I got the syntax wrong then. Thanks a bunch!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.