JavaScript Operator Precedence

25 Oct 2011

Operator precendence is the order in which operators are evaluated within an expression. For example, take this:

var leftStart = 5,
width = 2;
var left = leftStart - width / 2;

Now, what are we actually doing here? Is it:

var left = (leftStart - width) / 2;


var left = leftStart - (width / 2);

The addition of brackets would have made the original code more explicit, but is noisier and requires more typing. Reviewing JavaScript operator precedence shows that the division operator has higher precedence over subtraction, so in the above two examples we're going to get the same result as in the second snippet.

The remaining question is - why bother? By being explicit with brackets, you remove any ambiguity, despite having to type a little more. But I'd argue that not understanding precedence means you're leaving yourself open to bugs, and in more complicated examples the character noise will obscure the meaning of the code you're writing.

Feedback or questions on this post? Create an issue on GitHub.