Using the Associative Property in JavaScript Functional Compositions

Kyle Shevlin
InstructorKyle Shevlin

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 3 years ago

This lesson teaches you what the associative property is, the mathematical principle that proves the grouping of values in when adding or multiplying does not affect the result and applies it to functional composition. This lesson will demonstrate how we can achieve the same composition with different groupings of smaller compositions. This gives us confidence in our code and the ability to create even greater complexity with compositions.

Instructor: [0:00] Functional compositions obey the associative property of mathematics. Let me demonstrate. In addition and multiplication problems, if there are two or more occurrences of the same operation, then how we group the numbers doesn't matter.

[0:13] If I take the equation 1+2+3, I can group 1 and 2 together and add them to 3, or I can group 2 and 3 together and add them to 1. Each of these equations is equivalent.

[0:24] The same thing occurs with our functional compositions. I'm going to import a composed functions and some curried functions to make some compositions with. Just like our math problem before, I can create a composition with scream, exclaim, and repeat.

[0:41] Now, I'm going to save a string variable that we can pass into all our compositions. If we log out our first composition, we should see in the terminal, "I love Egghead! I love Egghead!" Both with exclamation points.

[0:53] Now, the associative property allows us to make sub-compositions within our composition to create the same functionality. We'll start by making a composition of repeat and exclaim. If I then create a composition with repeat excitedly and scream and pass it the same string, I'll get the same result.

[1:17] The other sub-composition we can make is to combine exclaim and scream. We'll call it "scream loudly," even though that seems a bit redundant. We can now use scream loudly in a composition with repeat, pass it our string and get the same result.

[1:36] The associative property allowed us to achieve the same results with each of these because we didn't change the order of operations. We only changed the grouping of the functions through sub-compositions.