Skip to content
Related Articles

Related Articles

JavaScript Grouping operator
  • Last Updated : 11 Sep, 2020

Below is the example of the Grouping operator.

  • Example:




    <script> 
        function gfg() { 
         // 3 * (2 + 3)
        let value1= 3 * (2 + 3);
             // (3 + 2) * 3
        let value2= (3 + 2) * 3;
        document.write(value1 + "</br>" + value2);
        
        gfg(); 
    </script>                    
  • Output:
    15
    15

    The Grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. This operator can only contain expressions. The parameter list is passed to function within this operator which will treat it as an expression.

    Syntax:

    ( )

    This ( ) operator controls the precedence of evaluation in expressions

    Below examples illustrates the Grouping operator in JavaScript:
    Example 1: Function as a statement and exception. In the below code JavaScript considers a function as a statement if it is not preceded by any other statement. But applying a grouping operator that has the highest precedence over any other operator considers the function as an expression and hence it gets fully evaluated.






    <script>
        function(x){ return x };
        // SyntaxError: Function statements 
        // require a function name.
      
      
        // function as expression
        (function(x){ return x });
        // This will run without any exception.
    </script>                    

    Example 2: With and without grouping operator.




    <script> 
        function gfg() { 
        // 5 * 5 + 5
        // 25+5
        // 30
        let value= 5 * 5 + 5 ; 
        document.write("Without grouping operator: " + value);
      
        // 5 * (5 + 5)
        // 5*10
        // 50
        let value1= 5 * (5 + 5);
        document.write("</br>With grouping operator: "+ value1);
        
        gfg(); 
    </script>                    

    Output:

    Without grouping operator: 30
    With grouping operator: 50

    full-stack-img

    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :