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;
//...