Map() vs filter() vs forEach()

let food = ['mango','rice','pepper','pear'];

map( ) : 

>return a new array containing the boolean result.

>it returns new array without mutating the old array

let newfood = food.map((foodItem=> 
{
    return foodItem == "mango"
});
console.log(newfood);

>map has the ability of chaining

eg. of chaining

// multiply each element with 2 and return only those element which are greater than 10

let arr = [234,5,6,7]

let newelement1 = arr.map((ele,index,array)=>
{
    return ele*2
}).filter((ele)=>{
    return ele > 10
});
console.log(newelement1);


filter( ) : 

>return a new array containing only those elements which passed the criteria.

>it returns new array without mutating the old array

let newfood = food.filter((foodItem=> 
{
    return foodItem == "mango"
});
console.log(newfood);


forEach( ) : 

>does not change the array and return undefined

> no chaining ability

let newfood = food.forEach((foodItem=> 
{
    return foodItem == "mango"
});
console.log(newfood);

0 Comments