(ES6) ES6 (2016)

MapForeach (MP60)

   1:  // Use forEach for side effects
   2:  const cartItems = ['apple', 'banana', 'orange'];
   3:  cartItems.forEach(item => {
   4:      addToCartDOM(item); // hypothetical function to update UI
   5:  });
   6:  
   7:  // Use map when you need a transformed array
   8:  const itemLengths = cartItems.map(item => item.length);
   9:  console.log(itemLengths); // [5, 6, 6]
  10:  
  11:  



Difference Between map() and forEach() in JavaScript

Feature map() forEach()
Return value Returns a new array Returns undefined
Purpose Transformation of array elements Side effects (like logging)
Chainability Can be chained with other methods Cannot be chained (returns undefined)
Immutability Creates new array (immutable) Modifies original array (mutable)





MapForeach context:






ES6 context:



Comments ( )
Link to this page: http://www.vb-net.com/JavascriptES6/MP60.htm
< THANKS ME>