article

native JavaScript Array method - Array.forEach()

[WHAT]

  1. [] by Don Sagrott, founder @ sospep.com -
  2. [] very similar to a for loop, BUT takes a callback function as an arguement,
  3. [] walks through each item of the array and executes the given callback function on that element
  4. [] forEach method modifies the original array with the specified callback functionality

[WHY]

  1. [] this article is intended to be a quick 1 page reference to the array method forEach
  2. [] along with a simple explanation of the method
  3. [] and a simple code example ( with context )
  4. [] of using the foreEach VS a for loop - we dont have to write/manage the index code,

[WHERE]

  1. ] READ THE FULL ARTICLE
    1. ] see below

[WHEN]

  1. [] 2017-10-13 -
  2. [] 2019-11-23- updated, split into individual articles

[EXAMPLE]

  1. [] The Array we will be working with is named 'cars' and is defined below. It contains a list of car model names, each array element is a "string" value and there are 5 initial elements.

var cars = ["corvette", "camaro", "mustang", "charger", "GTR"] ;

  1. [] forEach element in the array, we will modify the element by capitalizing the first letter of each car name that is currently in the array

cars.forEach( function(element, index){

  element.charAt(0).toUpperCase()+ element.slice(1);

})

console.log(cars);

// [ Corvette, Camaro, Mustang, Charger, GTR ]

[HOW-TO]

  1. [] use forEach - to iterate the example cars array and modify it by capitalizing the first letter of each car name listed in the array
  2. [] in the example we pass an anonymous function as a callback to the forEach method
  3. [] the arguements (element and index) are provided by the forEach method and refer to the individual array element that is passed and the array index value,
  4. [] you can name these arguements whatever you like ( ele, idx), ( car, i )
  5. [] REMEMBER the forEach methods given callback operates on the original array, so any changes made will permanently alter the original data

[REFERENCE]

  1. [] # # - CREATE-article# 5763 (this)
  2. [] MDN - Array.prototype.forEach() -

[RELATED]

  1. [x] # # - JavaScript Array Methods - overview article describing some of the most commonly used JavaScript Array methods
  2. [x] # 5764 - Array.map()
  3. [x] # 5772 - Array.reduce()
  4. [x] # # - Array.filter()
  5. [x] # # - Array.find()
Details Photos Edit more

Details

ID: 5763

NAME: JavaScript-Array-Methods-forEach

DESCRIPTION: JavaScript-Array-Methods-forEach - by Don Sagrott, founder @sospep.com - using the native JavaScript array method of forEach to manipulate your JavaScript arrays

AUTHOR: article.author/s

EDITOR: article.editor/s

PUBLISHER: article.publisher/s

STATUS: Write

PRIORITY: -5

OWNER ID: 75

Content Photos Edit more

photos

page_photo

actions

Email Email-Owner SMS and