Why var i = 15,4; generates an error? After all, first, the assignment must be executed, and then the operator returns 4. Or how does it work? Maybe not an operator in this context? Explain, please.
|
2 answers
Refer to the specification . The syntax for using var is as follows:
VariableStatement [Yield, Await] :
var VariableDeclarationList [+ In,? Yield,? Await] ;
VariableDeclarationList [In, Yield, Await] :
VariableDeclaration [? In,? Yield,? Await]
VariableDeclarationList [? In,? Yield,? Await] , VariableDeclaration [? In,? Yield,? Await]
VariableDeclaration [In, Yield, Await] :
BindingIdentifier [? Yield,? Await] Initializer [? In,? Yield,? Await] opt
BindingPattern [? Yield,? Await] Initializer [? In,? Yield,? Await]
This shows that in this case it is the BindingIdentifier that is separated by a BindingIdentifier .
The number 4 not an identifier, therefore, a syntax error is shown.
- Do I understand correctly that there is no universal rule? And you need to know the syntax of each instruction to prevent such errors? - Topik
- @Topik, it is formally possible to be attached to the priority of operations, the comma is the lowest priority. However, in this case, it will be necessary to remember the priorities of all operations :-) But there is nothing in the specification about priority. - Grundy
- I do not understand where is the priority. After all, with var "," is no longer an operator, but a separator and an identifier is expected after it. So knowing the priority here will not help. - Topik
- @Topik, so you answered your question :-) - Grundy
- I just wanted to know from you that my guesses are correct. - Topik
|
var declares a variable and optionally assigns a value to it. A declaration is a statement (statement), not an expression, and after the decimal point syntax in a declaration, only other variable declarations are possible (optional with assignment). This is how it works:
var i; i = 15,4; // Присваивает 15, возвращает 4. console.log(i); Now, assignment occurs first, then the second operand is returned.
- "second operand"? I do not think. - Igor
- @Igor And how do you call the four in this context? Here, for example, the definition from MDN : "The operator comma performs each of its operands (from left to right) and returns the value of the last operand." - vsemozhetbyt
- Look at the value of the variable
i. - Igor - So I do not argue that
iassigned15. I mean,i = 15,4;returns4. Check in the browser console or Node.js. These are two independent things: assigning15variableiand returning the value computed by the comma operator (in this case,4). - vsemozhetbyt pm - It would be nice to add to the answer that the string
i = 15,4returns4, so that it would be visible in the browser console. - Stepan Kasyanenko Feb.
|
var i = (15,4);- Doigrales 6:54 pm