Loops are used in computer science to repeat a sequence of instructions until a condition is met.

forEach loop

There are many different types of loops that you can create in JavaScript, but a popular one is called the forEach loop. This loops allows the computer to iterate over an array (a container of elements) for each element in the list.

The forEach loop calls a callback function on every element in an Array in ascending order.

// Arrow function
forEach((currentValue) => { ... } )
forEach((currentValue, index) => { ... } )
forEach((currentValue, index, array) => { ... } )

// Callback function
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function callbackFn(currentValue) { ... })
forEach(function callbackFn(currentValue, index) { ... })
forEach(function callbackFn(currentValue, index, array){ ... })
forEach(function callbackFn(currentValue, index, array) { ... }, thisArg)
  • forEach: The name of the method that loops through the elements of an array.
  • currentValue: The current element in the array that is being iterated on. This value will change with every iteration of the method/loop. You can name this parameter any name.
  • index: Holds the index value of the current element that is being iterated on. This is an optional parameter. You can name this parameter any name.
  • array: The array the forEach method is iterating on
  • thisArg: Value to use as this when executing callback.
  • callbackFun: The function or block of code executed on each method/loop iteration.

As seen above, there are many ways to use the forEach method and define the callback function. The most concise way to define a callback function within the forEach method is through the use of arrow functions expressions.

Arrow Functions

Arrow functions expressions are an alternative way to define and call a function. They use the symbol => to point to a function expression. Let's take a look at a few examples comparing traditional functions and arrow functions:

// Traditional Function
function (a, b){
  return a + b + 100;

// Arrow Function
(a, b) => a + b + 100;

// Traditional Function (no arguments)
let a = 4;
let b = 2;
function (){
  return a + b + 100;

// Arrow Function (no arguments)
let a = 4;
let b = 2;
() => a + b + 100;

You can practice and explore more with the forEach() method and arrow function expressions in the forEach demo from MDN Docs.

Fork me on GitHub