@kangoo1707
Snr. Front End
Nothing here yet.
Nothing here yet.
No blogs yet.
In the land of OOP, when reading code, you have a very natural way of expressing things: Subject + Verb + Object. For example: Peter. say ( 'Hello World' ); John.takeOut( 'garbage' ).andDumpItTo( 'the dumpster' ); To do that, you must define a class Person and then define methods such as say(string), takeOut(what) and andDumpItTo(where) before you can instantiate objects like Peter and John. It's very easy to decompose objects in the world to smaller one, and that's the selling point of OOP. In the functional land, you have quite a bit different way to do things: Verb + Object + Subject. This would then become: say ( 'Hello World' , Peter); Or in a curried versions, you have var action = say( 'Hello World' ) var result = action(Peter); What is the return value of say('Hello World')? It's a function that can take another object (Peter) and then output the real result. So, what about John, given that he has to perform 2 actions. You can use a technique called function composition var actions = takeOut( 'garbage' ) |> andDumpItTo( 'the dumpster' ); var result = actions(John); The |> is just an imaginary symbol indicates that results will pipe through each function, one by one: the result of takeOut('garbage', John) will be passed as the parameter of andDumpItTo('the dumpster', ...) You will notice that, in the functional land, verbs play a very important role. You work with verbs all the time, and it's often the first thing you see in a statement. You can create a function easily and then apply the object later. A functional programmer thinks in functions such as takeOut(what, byWho) and andDumpItTo(where, whatToDump), and then he uses composition to make the whole program works. Another concept is higher order function. Let me remind you of the Array.sort function. var numbers = [ 3 , 2 , 7 , 9 , 1 , 0 ]; var comparator = (a, b) => a - b; var sortedNumbers = numbers.sort(comparator); What do do pass to the sort() function? Another function. While this is unusual in OOP, people do it ALL THE TIME in FP. You can think of it like strategy pattern in OOP. So, as you can see, in FP, people love functions. They create it in various ways and functions stand freely as first-class citizens. It does not need an object to tells it what to do. Function can be passed to another function, it can be the result of another function. A function should be pure, that is, the output is calculated based on the input. Let's take a look at this one: var sayPure = (name) => 'Hello ' + name; var sayImpure = (name) => this .greeting + name; Well, what are the results when I pass 'World' into sayPure and sayImpure? If you can answer that confidently, then you'll understand the importance of pure functions when it comes to testability and ease of reasoning. Isn't the impure version what you always do in OOP?