1

Today I had a job interview on JS and one of the questions was

What is the value of a

var a = (3,5 - 1) * 2;

Hmm I assumed its 8 (the chrome dev console also gives it 8) but I don't know why it is eight. Why the 3 is omitted? I mean of course you can't do any operations with it but still, it disappears, or I am wrong?

Please go easy on me. I am trying to understand. Any articles on this kind of operations would be highly appreciated

Nicholas
  • 3,529
  • 2
  • 23
  • 31

3 Answers3

2

As per the Comma Operator | MDN,

The comma operator evaluates each of its operands (from left to right) and returns the value of the last (right-most) operand.

So, var a = (3,5 - 1) * 2; returns 4 * 2 = 8

tanmay
  • 7,761
  • 2
  • 19
  • 38
2

3,5 it's not 3.5 (float). See comma operator

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

3,5 equals 5.

(3,5 - 1) * 2 translates to (5 - 1) * 2 which is 8.

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
1

See this reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

The comma operator evaluates all of the expressions listed and returns the last one. So your expression simplifies to

(5 - 1) * 2

n8wrl
  • 19,439
  • 4
  • 63
  • 103