2

Please help me to understand the code below, how the values of 'a' , 'b' and 'c' are calculated.

var a = (1,5 + 10) * 5; //returns 75
var b = (0, "150", 30, 20, 38 + 10); //returns 48
var c = (5 & 3 + 10); // returns 5
Prakash Upadhyay
  • 423
  • 1
  • 3
  • 14

2 Answers2

6

a is set to be (1, 5 + 10) * 5. At the top level, it’s a multiplicative expression, multiplying 1, 5 + 10 by 5. 1, 5 + 10 uses the comma operator, which first evaluates 1, discards it, and then evaluates 5 + 10, which evaluates to 15, which is then multiplied by 5, yielding 75.

b works similarly, except it’s just got a lot of commas. It evaluates a lot of things, discards all their results, and finally goes on to evaluating the last one, 38 + 10, which gives the result 48.

c evaluates 5 & 3 + 10. & has a lower precedence than +, so it’s actually 5 & (3 + 10). 3 + 10 is 13, which is 1101 in binary; 5 is 101 in binary. Doing a bitwise AND on these two values yields 101, which is again 5, which is the result.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
1

To understand it more easily, "the comma operator evaluates each of its operands (from left to right) and returns the value of the last operand."

So (a, b,c, ... z) will evaluate everything but only return z.

In your example:

var a = (1,5 +10)*5;

1 is evaluated, then 5+10 (which is 15);15 is then returned and multiplied by 5.

The & operator does a bitwise AND on the numbers (ie. compare two binary numbers and for each position, return 1 if both numbers are 1).

0101 //5
1101 //13

0101

The last number is 5 in decimal

Alberto Rivera
  • 3,652
  • 3
  • 19
  • 33