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!
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
There must be at least one comma, space, or tab between variables, and one or more spaces or tabs are the same as a single space. Consecutive commas are not permitted before a variable name.
JavaScript uses a comma ( , ) to represent the comma operator. A comma operator takes two expressions, evaluates them from left to right, and returns the value of the right expression. In this example, the 10, 10+20 returns the value of the right expression, which is 10+20. Therefore, the result value is 30.
The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With