-1

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();   
          }
}
5
  • 3
    First guess is that variable is undefined Commented Oct 25, 2013 at 22:06
  • 1
    You haven't defined variable. Did you intend to check if existingthread == null instead? Commented Oct 25, 2013 at 22:06
  • open your developer tool bar and check console.If you do you will see the error "variable is not defined". Commented Oct 25, 2013 at 22:07
  • 1
    By the way, typeof is an operator, not a function. Commented Oct 25, 2013 at 22:07
  • 4
    Look. At. The. Console. Commented Oct 25, 2013 at 22:07

3 Answers 3

2

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.

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

Comments

2

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

Comments

2

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.

Comments

Your Answer

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.