JavaScript - Grouping Operator
JavaScript - Grouping Operator
JavaScript Grouping Operator
Thegroupingoperator in JavaScript controls the precedence of the evaluation in expressions. It is denoted by parenthesis (), and you can put the expression inside that to change the expression evaluation order. It helps to evaluate an expression with lower precedence before an expression with higher precedence.
Syntax
You can follow the syntax below to use the grouping operator
( exp )In the above syntax, the βexpβ is an expression to change the precedence of evaluation.
let res1 = 4 + 5 * 6; // 4 + 30
let res2 = (4 + 5) * 6; // 9 + 6The multiplication (*) operator in JavaScript has higher precedence than the addition (+) operator. So, when the above code evaluates the first expression, it will multiply 5 and 6 and add the resultant value to 4.
In the second expression, we grouped the (4 + 5) expression using the grouping operator to provide it with higher precedence than the normal operator. So, it adds 4 and 5 first and multiplies the resultant value with 6.
Example
It will produce the following result β
Result 1: 34
Result 2: 54Immediately Invoked Function Expressions (IIFEs)
To define animmediately invoked functionin JavaScript, we use thegroupingoperator. The anonymous function definition is put inside the grouping operator. These functions are also called self-executing functions.
(function () { return 5; })();In the above example, the function definition βfunction () { return 5;}β in put inside the grouping operator.
Example
In the example below, we have defined the self-executing function statement using the grouping operator.
The first expression divides 10 by 5 (returned value from the function) and adds the resultant value, which is 2 to 5.
The second expression adds 5 and 10 first and divides the resultant value with the value returned from the function.
It will produce the following result β
Result 1: 7
Result 2: 3In simple terms, the grouping operator is used to group the sub-expressions to change its evaluation precedence over the normal precedence.
Grouping Operator with Logical Operators
Thegroupingoperator in JavaScript can also be used to group expressions with logical operators. For example, in the following expression, the && operator has a higher precedence than the ||operator. So, the expression will be evaluated as follows:
false && false || true; // trueHowever, if we add parentheses around the ||operator, the expression will be evaluated as follows:
false && (false || true); //falseThis is because the grouping operator overrides the normal operator precedence, so that the ||operator is evaluated first.
Example
This example demonstrates that how a grouping operator changes the precedence of OR operator to be evaluated before AND operator. The expression uses the logical operators.
It will produce the following result β
Result without grouping operator: true
Result with grouping operator: false