JavaScript comma and variable evaluation
javascript
Solution
In `alert( i = 0, j = 1, k = 2 );` the commas are separating the function arguments.
In a general expression it works like the book says:
alert( ( i = 0, j = 1, k = 2 ) );
Note that all the book is saying is that the expression `"i = 0, j = 1, k = 2"` `"evaluates to 2"` In many contexts you need to put that expression inside parentheses for it to be a single independent expression like the book intends it to be.
In variable declarations, comma again has special behavior. It allows you to write shorter declarations because you don't have to repeat `var`:
`var a; var b; var c;` and `var a, b, c;` are equal. So are `var a = 5; var b = 6; var c = 7;` and `var a = 5, b = 6, c = 7;`
Comma has also special behavior in array and object literals:
var a = [1,2,3] //Creates an array with elements 1, 2 and 3
var a = [(1,2,3)] //Creates array with one element: 3
var b = {
key: value, //Comma is separating the key-value pairs.
key2: value2
}
Problem
The book "JavaScript:The Definative Guide, 6th edition" in section 4.13.5 states that - ``` "i=0, j=1, k=2; evaluates to 2" ``` But when I display the value like this - ``` var x = i=0, j=1, k=2; alert(x); ``` or ``` alert(i=0, j=1, k=2); ``` The value `0` is displayed. I experimented, and whatever the value of `i` is set to, is displayed. The book seems to be wrong. Can anyone explain what the book meant by saying the statement `evaluates to 2`? Is it wrong? Thanks!