Why does
if (prev = this.Prev()) {
...
}
work but
if (var prev = this.Prev()) {
...
}
does not? this.Prev() is a method for a Point object which returns a reference to a previous Point if it exists, and false if it does not. I don’t want to declare the variable to be global, and I don’t want something verbose like:
var prev = this.Prev();
if (prev) {
...
}
EDIT: What’s the most elegant way to do something like what I am trying?
This happens because the
ifstatement expects a expression:Syntax:
varis a statement that’s why you get aSyntaxError.Your first example works because an assignment is a expression (AssignmentExpression)
Edit:
Let me quote this part:
I understand your concern, an assignment made to an undeclared identifier may end up creating a property on the global object, moreover with the ECMAScript 5th Strict Mode, an undeclared assignment will cause a
ReferenceError, breaking your codeVariables in JavaScript are declared before the actual code execution, all occurrences of the
varstatement are bound to the current Variable Object, and they are initialized withundefined, you can’t really declare a variable conditionally.