Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

JavaScript Comma operator

  • Difficulty Level : Basic
  • Last Updated : 09 Sep, 2020

Below is the example of the Comma operator.

  • Example:

    Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!




    <script> 
        function x() { 
            document.write('one'+"</br>"); 
            return 'one'
        
        function y() { 
            document.write('two'+"</br>"); 
            return 'two'
        
        function z() { 
            document.write('three'+"</br>"); 
            return 'three'
        
      
        // Three expressions are 
        // given at one place 
        var x = (x(), y(), z()); 
      
        document.write(x); 
    </script> 
  • Output:

    one
    two
    three
    three

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:




<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>

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:




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

Output:

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera



My Personal Notes arrow_drop_up
Recommended Articles
Page :