I am studying the use of the comma to separate variables:
var suma = 10, iterador;
I don't understand why I get error when I do:
var resultado = contador = 20, contador += 5;
If I understood correctly, the expression is evaluated from left to right, so when I try to increase the counter variable, it should already be declared and initialized with a value of 20. Thanks
The statement syntax
var
does not support the operator+=
.Note that the syntax of
var
is as follows:The operator
+=
does not appear in its definition.The normal thing is to use
var
to initialize a variable and optionally give it a value.If you are going to give it a second value, it is normal to do it in another sentence:
EDIT: Although indeed, the syntax of
var
does not allow the operator+=
, the syntax of an expression (what would go in value1, value2, ..., valueN) does allow it; As String Manolo points out in his other answer, so yes, this could be done:or even
Now the question that should be asked is, why do you want to make two different assignments to the same variable in a single sentence, instead of making a single assignment with a value of 25 to the counter? The normal thing would be to initialize the variable once, and then alter its value in successive statements.
More info:
You can do it.
The problem is that the syntax is not supported because you omit the variable=
See for example:
If you put a comma in var the format of identifier = value is expected.
As a value it can be an expression, you can do the sum, a function call, or whatever you want to leave there something that is valid to assign to the identifier.