I'll try to do my best explanation by step by step examples.
Step 1
Function definition
In javacript you can define a function with 2 different syntax
function inc(number) {
return number + 1
}
or
const inc = (number) {
return number + 1
}
// or simplifed
const inc = (number) => number + 1
Those 2 syntax are more or less equivalent but the second one is stays that you have a constant called inc (so a variable) that have a pointer to a piece of memory that contains a function.
So, inc
is a variable that contains (as value) the function payload.
Step 2
This step is not related with the previous one
Supposing that we have an array and we want to increment each element into a new array we can use the function map.
Map is a function that creates a new array populated with the results of calling a provided function on every element in the calling array.
Mozilla Reference
const result = [1,2,3,4].map((number) => number + 1)
console.log(result)
Step 3
Let's make ingredients together
We have have a inc
function and we want to use that function in our map
.
We can do a very simple things.
const inc = (x) => x + 1
const result = [1,2,3,4].map(number => inc (number))
console.log(result)
Step 4
Let's try another approach.
Forget for a moment what we have done on step 3, trying using our inc
function. We will try another approac.
At step 1 we have seen that a function is defined as follows.
const inc = (number) => number + 1
The semantics around the equal sign is quite powerful and is saying:
the expression inc
is equivalent to
the expression (number) => number + 1
We can take our inc
function definition and the Step 2 code.
const inc = (number) => number + 1
const result = [1,2,3,4].map((number) => number + 1)
On the right side of both lines we have a duplicated expression:
(number) => number + 1
And first line says that an equivalent expression is inc
. Trying to apply this approach the results is:
const inc = (x) => x + 1
const result = [1,2,3,4].map(inc)
console.log(result)
when you are trying to read a code written in this way you can imagine to inline inc
label with its own expression.
Bonus
Let's apply the approach with more than 1 parameter
Trying to apply this approach for 2 parameter function we need another usecase. Given an array of numbers we want the sum of each number.
To achieve that we'll use the standard reduce
function.
Mozilla Reference
const result = [1,2,3,4].reduce((a, x) => a + x, 0)
console.log(result)
now we can extract a sum function and replace the expression with it's label.
const sum = (a, b) => a + b
const result = [1,2,3,4].reduce(sum, 0)
console.log(result)