JavaScript Comma operator

A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++, Java, etc. This 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:

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    function x() {
        document.write('Welcome');
        return 'Welcome';
    }
    function y() {
        document.write('to');
        return 'to';
    }
    function z() {
        document.write('Geeksforgeeks');
        return 'Geeksforgeeks';
    }
  
    // Three expressions are 
    // given at one place
    var x = (x(), y(), z());
  
    document.write(x);
</script>

chevron_right


Output:

In the output, first of all the function x() is executed then y() and lastly z(). Finally, comma operator returns rightmost expression.

The most useful application of comma operator is in loops. In loops, it is used to update multiple variables in the same expression.

Example:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

for (var a = 0, b =5; a <= 5; a++, b--) {
  document.write(a, b);
}

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.