JavaScript Comma Operator
A comma operator (,) mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. A comma operator is used as a separator for multiple expressions at a place that requires a single expression. When a comma operator is placed in an expression, it executes each expression and returns the rightmost expression.
Syntax:
Expression1, Expression2, Expression3, ....so on
In the above syntax, multiple expressions are separated using a comma operator. During execution, each expression will be executed from left to right and the rightmost expression will be returned.
Example: Below is an example of the Comma operator.
javascript
<script> function x() { console.log( 'one' ); return 'one' ; } function y() { console.log( 'two' ); return 'two' ; } function z() { console.log( 'three' ); return 'three' ; } // Three expressions are // given at one place var x = (x(), y(), z()); console.log(x); </script> |
Output:
one two three three
Example: This example shows the use of the comma operator in Javascript.
javascript
<script> function x() { console.log( 'Welcome' ); return 'Welcome' ; } function y() { console.log( 'to' ); return 'to' ; } function z() { console.log( 'Geeksforgeeks' ); return 'Geeksforgeeks' ; } // Three expressions are // given at one place var x = (x(), y(), z()); console.log(x); </script> |
Output:
Welcome to Geeksforgeeks Geeksforgeeks
In the output, first of all, the function x() is executed then y(), and lastly z(). Finally, the comma operator returns the rightmost expression.
Example: The most useful application of the comma operator is in loops. In loops, it is used to update multiple variables in the same expression.
javascript
<script> for ( var a = 0, b =5; a <= 5; a++, b--) { console.log(a, b); } </script> |
Output:
0 5 1 4 2 3 3 2 4 1 5 0
We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.
Supported Browsers:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera
Please Login to comment...