JavaScript and Associativity

Thu May 18 2017

Ok. Now one would perhaps expect this code to evaluate as “slayer” logged four times in the console. Or maybe “slayer”, “anthrax”, “iron maiden” and “motorhead” cascading down the log. Thats perfectly reasonable and logical.

BUT ~ here is a quirky thing about JavaScript and its called associativity.

This code actually prints out motorhead 4xs to the console. JavaScript is evaluating this code from right to left and not left to right, how you would normally expect. If you go to the Mozilla Developer Network and search for "Operator Precedence and Associativity" you will find a super helpful chart, one that lists the order in which JavaScript determines code precedence.

Here is another good example.

var math = 4 + 2 * 5;


You would expect 30 to be logged... but thats again, not whats going on. This code is being evaluated with the multiplication happening first, then the addition, resulting in the answer of 14. Because multiplication is HIGHER on the precedence list than addition. That chart on the MDN is legit.