Operator precedence determines the order [Operator precedence determines the order]2 and binary operators are executed. In many situations, knowing basic mathematical operator precedence (for +,-,*, etc) is enough. In other situations not knowing the specifics of language can lead to hard to find errors. Quickly, in JavaScript what does 'the boogeyman ' + false ? 'is scary' : 'is not scary' evaluate to?

At first glance this statement might appear to produce the phrase ’the boogeyman is not scary’. Unfortunately, executing in a JavaScript interpreter—try it here—reveals that the actual result is ‘is scary’.

We get a different result from the expression due to JavaScript’s operator precedence rules. In our case the binary ‘+’ operator has a higher precedence than ‘?’ and is executed first. Knowing that ‘+’ goes first we can break down the execution of the above statement into a couple steps:

  1. 'the boogeyman ' + false which yields 'the boogeyman false' thanks JavaScript’s type coercion rules for the ‘+’ operator.
  2. 'the boogeyman false' ? 'is scary' : 'is not scary' which yields 'is scary' due to JavaScript’s truthiness rules declaring ’the boogeyman false’ as a true/truthy value.

Resolving the bug and getting the answer we want is accomplished by using parenthesis to force the ternary to be executed before the addition,

'the boogeyman ' + (false ? 'is scary' : 'is not scary').

In many languages the first expression we wrote wouldn’t be possible to write due to lack of support for automatic type conversion between the relevant types. JavaScript, however, gives us the means to introduce subtle and hard to find bugs in web applications. This kind of bug is hard to find since a quick glance at the line won’t reveal an issue unless the reviewer is specifically looking for the issue.

For experienced developers the above may have been self-evident. Operator precedence is worth keeping in mind though because of its importance and the subtly of the bugs caused by it.

(For a reference Mozilla has a table describing JavaScript’s operator precedence rules.)