tim.baker
tim.baker

Reputation: 3307

Why doesn't this simple JavaScript if statement work?

This if statement doesn't work. I would expect it to write "if" as the variable should be empty. Or failing that I would expect "else" but there are neither

You can also see it on JSFiddle in full not working glory

I think JSFiddle maybe having problems at the moment

checkforthread();

function checkforthread() { // Check to see if it is a new or existing chat

// Set the variable
        var existingthread = "";

      document.write("test");

      if (typeof(existingthread) == 'undefined' || variable == null) {
            document.write("if");
            gotostage3();   
            }
          else {
            document.write("else");
            gotostage3();   
          }
}

Upvotes: -1

Views: 1178

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

In JavaScript, if you try to take the value of an undefined symbol, you get a ReferenceError. That's what's happening here. variable is completely undefined, and so trying to take its value (so you can compare it with null) is failing with a ReferenceError. You can see this in the Dev Tools of your browser:

enter image description here

This aborts the script code being run, since it's not caught.

If for some reason you need to check if a symbol is defined, there is a way to do that: The typeof operator, which you're already using:

if (typeof existingthread == 'undefined' || typeof variable == 'undefined') {

If you apply typeof to a symbol you haven't defined, it doesn't throw an error; instead, you get back the string "undefined".


Note that typeof is an operator, not a function; no need to wrap its operand in parentheses.

Upvotes: 2

Darko
Darko

Reputation: 38880

If I assume that you mistyped and that variable is supposed to be existingthread, then what you are doing wrong is that existingthread is neither undefined nor null, it is an empty string!

you could simplify your if clause by just saying if (existingthread) { ... }, if I am guessing correctly what you are trying to achieve.

Upvotes: 2

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

variable is undefined and that's the same error being shown in JSFiddle.

Upvotes: 2

Related Questions