Published on

When order doesn't matter

Authors

Let's examine the following code blocks:

// Number Addition
2 + 5 + 3 === 2 + (5 + 3)
7 + 3 === 2 + 8
10 === 10
// String Concatenation
'a' + 'b' + 'c' === 'a' + ('b' + 'c')
'ab' + 'c' === 'a' + 'bc'
'abc' === 'abc'

Note the equations on line 4 in both examples. The results on the left hand side (LHS) are the same as the results on the right hand side (RHS) despite different intermediate results on line 3. This is because addition for numbers and concatenation for strings does not depend on the order of evaluation.

When the order of evaluation is irrelevant for an operation of a particualr data type—meaning that the end result is the same no matter which part of the expression is evaluated first—then the operation is said to be associative with respect to that particular data type.

For associative operations, you can safely remove the brackets because the end result will be the same no matter which sub-expression the compiler decides to evaluate first.

2 + 5 + 3 === 2 + 5 + 3
'a' + 'b' + 'c' === 'a' + 'b' + 'c'

Now armed with the basic idea, you should go learn more about the associative property because it is one of the fundamental properties in the domain of mathematics, and functional programming by extension.