Guild Through JavaScript Array Methods — 01
Array.map() method.
The map
method will take a callback function as an argument and called for every element in the given array. The map
function will return a new array by the result of the calling function. The map
function will not modify the original array. Hence it is an immutable function.
Let’s start with a simple example to illustrate all the above points.
Now we clear that callback function takes the current processed value as the first argument and processed it and return the new value. Then it will push to the new array.
Take a min and imagine what if we didn’t pass any parameter to map function?
fruits.map(()=> {})
There are few optional parameters in the callback function. I want to mention that it takes the 2nd argument in the callback function is the index of the current called value from the array.
Array.reduce() method
As the method name spoke, this method will reduce to one value. More specifically this reduce
method will execute the reducer function
that we provide as the callback function and call on each element. Finally, reduce
function will return a single value.
This reducer function needs 2 parameters. Within the reducer function
we need to return the value to use as the accumulator in the next iteration (Unless it will return the undefined
). The first time, array’s first element is the accumulator and 2nd element is the current value. (This will only happen at the first time execution of the reducer
function and if didn’t provide a initialValue
)
Let’s see it from an example.
We saw how it works. Let’s see a meaningful example. If we want to get the summation of this array we can change the reducer
function as below.
const reducer = (acc, val ) => { return val+acc; }
But it is good to know that there are 2 other optional parameters accept by the reducer
function. Those are currentIndex
and the array
.
The reduce
function takes 2nd argument that reducer function and initialValue
.
Special Scenarios:
Scenario 01:
The array has only one value.
No initial value in
reduce
function.Result: solo value in the array will return.
const marks = [30]
const result = marks.reduce((acc,val)=> {
console.log(`current acc: ${acc}`);
console.log(`current val: ${val}`);
})
Scenario 02:
The array doesn’t have any value.
There is an initial value for
reduce
functionResult: Initial value will return.
const marks = []
const result = marks.reduce((acc,val)=> { },30)
Above both scenarios, the callback function will not be called.
If both not provided and then we get a TypeError.
Reference:
Main image credit