You are currently viewing Comma Operators in JavaScript | Explained

Comma Operators in JavaScript | Explained

Javascript Comma Operators

In this article, we will see what is javascript comma operators. A comma operator is a special operator; evaluated from left to the right-most operand.

Ex 1:

var result1 = (2,3) + (2,3); //3+3
document.write(result1); //6
  1. See the above code, we have created the variable “result1” using the var keyword and assigned the value as (2,3) + (2,3). In this list, the comma operator returns the right-most operand which is 3.
  2. So, the given expression executes 3+3 and return value 6.

Ex 2:

var a=0, b=0;
var c = (a=10, b=20, a+b);
document.write(c); //30
  1. In this example, we have created two variables ‘a’ and ‘b’, and both values are assigned 0.
  2. Then we created another variable “c” and assigned the value as “a=10, b=20, a+b” using the comma operator.
  3. The comma operator returns the right-most operand here the right-most operand is “a+b”.
  4. We printed variable c. So, the rightmost operand “a+b” is become executed and the output is 30

Leave a Reply