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,049
  • 1
  • 22
  • 30

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,556
  • 2
  • 18
  • 35
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
  • 33,668
  • 7
  • 72
  • 89
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,151
  • 4
  • 60
  • 101