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.

The Obscure Question
  • 1,134
  • 11
  • 26
  • 1
    Try doing `!==` or `typeof !==` See http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – aug Aug 28 '13 at 01: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". – nnnnnn Aug 28 '13 at 02:06
  • Hmm, it does seem to be a duplicate. I guess my search query was a bit off, but thanks to everyone who replied. – The Obscure Question Aug 28 '13 at 02:57

1 Answers1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209