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;
First question: IMO, using an assignment on the condition of the
ifstatement, might cause confusion, also ifmyVaris not declared previously with thevarstatement it might become a global variable.Second question: No, you aren’t re-declaring
Ya second time, actuallyYis defined before any assignment, it is hoisted to the top of its enclosing scope.This is how actually
varbehaves in your code:You can observe this behavior with the following example:
As you see, the
alertis before thevardeclaration in that function, but since thevarstatement is hoisted, theYvariable 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:Or even shorter, in a single
varstatement: