0

This code is to dynamiclly change the condition , however, this statement is recognized and interperted by chrome but not fx , how to fix the problem ? thanks

if a % 2 == 0 
  var condition = b == c  || b == d;
else 
  var condition = b == e  || b == f ;

if (condition)
  ......
2
  • Any variable declared as var someVar will be hoisted to the top of the scope, so you only need to use the var keyword once per symbol. Commented Feb 3, 2013 at 14:13
  • This code should work fine in Firefox. Can you link to a testcase that doesn't work? Commented Feb 3, 2013 at 18:07

2 Answers 2

4
var condition = (a % 2 == 0) ? (b == c  || b == d) : (b == e  || b == f);
Sign up to request clarification or add additional context in comments.

Comments

0

Write it like this:

var condition;
if (a % 2 == 0)
    condition = b == c  || b == d;
else 
    condition = b == e  || b == f ;

if (condition)
   ......

11 Comments

Because you got condition definied before you use it.
What purpose will that serve? It's an if-else conditional, either the if or the else will execute, so the variable gets defined inside one of them anyway...
I can tell how it is in C#, C++ and Java, when you want to use a variable out of an if else statement you have to define it before you use it.
But not in Javasript. In JS, a variable declared with var will always be pre-initialized with undefined, so even if the conditional doesn't evaluate to true and the variable never gets the chance to be given the supposed value, because the code never enters that unit, outside that unit, it's value will be undefined...
This actually isn't a bad answer, even though you didn't know why it is or isn't the right answer.
|

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.