
Comma Operator(,)
Is the comma operator same as comma within arrays, objects, and function parameters and arguments?
NO! It is completely different from them. Comma operator is expression separator where as semicolon (;) is a statement separator.
This operator evaluates each operand value from left to right and returns the last operand. As shown in the example, when we execute the valueOf()
method on the Object
, it returns the value as 30
i.e. last value of the operand.
Syntax
expr1, expr2, expr3…
What is it's use?
If you want to supply multiple parameters in a for
loop, this can be handy. It also allows you to use multiple expressions in a place where one expression is expected. Examples:
array
swapping without using a temporary variable.console.log
statements- Arrow (lamda) function
- Array
reduce()
method
Runtime Algorithm:
- Evaluate expression (exp)
- Perform ?GetValue(exp)
- Evaluate Assignment Expression (res)
- Return ?GetValue(res)
Ref: ECMAScript Comma Operator
GetValue()
must be called irrespective of the value being used or not; as it may have observable side-effects.
Note that, Operator precedence and associativity rules are applied to determine how operators are parsed.
Happy Learning!
![]() | ![]() | ![]() | ![]() |
Like | Comment | Save | Share |