The JavaScript grouping operator (()
) has the highest order of precedence. It is used to override the normal operator precedence (so that operators with lower precedence can be evaluated before an operator with higher precedence).
In the following example, division (/
) is carried out first as it has higher order of precedence than the addition operator (+
):
const x = 5 + 10 / 5; console.log(x); // 7
However, if you wanted to do the addition first and then division, you would have to use the grouping operator, for example, like so:
const x = (5 + 10) / 5; console.log(x); // 3
Although, the grouping operator has the highest order of precedence (when it comes to evaluating expressions), in some cases it may not be evaluated first. For example, one such case is when short-circuit evaluating an expression (i.e. conditionally evaluating an expression):
null && (1 && 'never reaches here'); // null 1 || (false || 'never reaches here'); // 1 1 ?? (false || 'never reaches here'); // 1
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.