JavaScript variable: var a =(3,4,7);

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

Can you please explain how we are getting output 7?

It's called comma operator. When you assign (3,4,7) to a variable 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 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));


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: