4
if(myVar = img.parent('a').length > 0){
    var Y = 1;
}else{
    var Y = 2;
}

When I run this code myVar (being announced for the first time) takes the value of img.parent('a').length > 0 and becomes either false or true depending on the case.

First Question:
Is this a correct way of defining myVar?

Second Question:
Am I defining Y for the second time? Is my second 'var' excess?
i.e. should i just write Y = 2;

1 Answer 1

7

First question: IMO, using an assignment on the condition of the if statement, might cause confusion, also if myVar is not declared previously with the var statement it might become a global variable.

Second question: No, you aren't re-declaring Y a second time, actually Y is defined before any assignment, it is hoisted to the top of its enclosing scope.

This is how actually var behaves in your code:

var Y; // declared and initialized with `undefined`

if (myVar = img.parent('a').length > 0) {
  Y = 1; // assignment
} else {
  Y = 2; // assignment
}

You can observe this behavior with the following example:

var Y = 'foo';
(function () {
  alert(Y); //alerts `undefined`
  var Y;
})();

As you see, the alert is before the var declaration in that function, but since the var statement is hoisted, the Y variable from this new scope is set up before the execution, when the Variable Instantiation process takes place.

The most straight forward approach, would be to declare and assign myVar:

var Y, myVar = img.parent('a').length > 0;

if (myVar) {
  Y = 1;
} else {
  Y = 2;
}
// Or Y = myVar ? 1 : 2;

Or even shorter, in a single var statement:

var myVar = img.parent('a').length > 0,
    Y = myVar ? 1 : 2;
//...
Sign up to request clarification or add additional context in comments.

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.