8
var a =(3,4,7);
console.log(a);  // Output is 7

Can you please explain how we are getting output 7?

2 Answers2

9

It's called comma operator. By wrapping the right hand expression in parentheses we create a group and it is evaluated each of its operands and returns the last value.

From MDN

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

The comma operator is useful when you want to write a minifier and need to shrink the code.

For instance,

print = () => console.log('add')
add_proc = (a,b) => a + b

function add(a, b){
  if(a && b){
      print();
      return add_proc(a,b)
  }
  else
  {
     return 0
  }
}

console.log(add(1,2));

could be minified using comma operator as below:

print = () => console.log('add')
add_proc = (a,b) => a + b

add = (a, b)=> a && b ?(print(),add_proc(a, b)):0

console.log(add(1,2));
Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103
0

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

Here , Seprates each Digits Ans As it is a Variable So it stores 3 then overlapped by 4 and finally 7 So final output is 7

rajat kumar
  • 25
  • 1
  • 8