Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript comma and variable evaluation

Tags:

javascript

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!

like image 300
A Bogus Avatar asked Mar 07 '13 09:03

A Bogus


People also ask

What is the advantage of a comma operator in JavaScript?

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.

Are commas allowed in variables?

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.

How do you use commas in JavaScript?

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.

How do you evaluate an expression in JavaScript?

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.


1 Answers

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
   }
like image 181
Esailija Avatar answered Nov 15 '22 07:11

Esailija