2

Why is the following not valid JavaScript?

if (var foo = (true || false)) {
    console.log(foo);
}
8
  • What do you expect this code to do? Commented Sep 3, 2014 at 11:38
  • Log true to the console. Commented Sep 3, 2014 at 11:39
  • Can you explain how you expect this output? How do you believe this code should be executed? Why do you think that a variable assignment would return a boolean value? Commented Sep 3, 2014 at 11:40
  • (true||false) evaluates to true. The assignment of foo evaluates to true. The if checks the conditional which is the result of the assignment, whcih is true. The body of the if "should" then run. Clearly it is not valid JS, but my question is why? Commented Sep 3, 2014 at 11:42
  • 1
    an assignment would return the value of the variable it was assigned to. if (foo = true) would return true. it is just that the var keyword can not be used in a comparison. it's a statement, not a function. Commented Sep 3, 2014 at 11:42

4 Answers 4

2

When you declare a variable in JavaScript the assignment will return the value of the new variable, so you can do something like this:

if (foo = (true||false)) console.log('Hello!');

> Hello!

Now if you call foo it will have a value of true:

console.log(foo);

> true

You cannot use the var private word, because if is a statement, not a function. If you want to be sure about the scope of your variable, then you have to declare it first:

var foo;
if (foo = (true||false)) console.log('Hello!');

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

Comments

1

Take a look here:

http://www.ecma-international.org/ecma-262/5.1/#sec-12.5

then here:

http://www.ecma-international.org/ecma-262/5.1/#sec-11

And conclude that the syntax isn't valid because of:

http://www.ecma-international.org/ecma-262/5.1/#sec-12.2

in relation (or rather lack thereof) to the above.

Comments

0

Try this :

 var foo = true || false;  
 if (foo) {
     console.log(foo);
  }

Place the declaration first and then check for the condition.

Comments

0

You can do like this:

var foo;//declare the variable first
if (foo = (true || false)) { //then assign the value for foo
    console.log(foo);
}

You cannot create variable declaration inside if statement.

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.