forEach

Function

Objectives

  • Describe and use the forEach function

  • Implement the forEach function

Print Array Values Doubled

var arr = [1,2,3,4,5,6];
function double(arr) {
  for(var i = 0; i < arr.length; i++) {
    console.log(arr[i] * 2);
  }
}
double(arr);
 var arr = [1,2,3,4,5,6];
 forEach(arr, function(number) {
     console.log(number * 2);
 });

Double With forEach

function forEach(array, callback) {
  // To be implemented
}
// Callback signature
function callback(curElement, currentIndex, array) {
  // Implemented by the caller of forEach
}

forEach Function Definition

var strings = ["my", "forEach", "example"];

var result = "";
forEach(strings, function(str, index, array) {  
  if (array.length - 1 !== index){
    result += str + " ";
  } else {
    result += str + "!!!";
  }
});

forEach Example With All Callback Parameters

result = "my forEach example!!!"

var strings = ["my", "forEach", "example"];

var result = "";
forEach(strings, function(str, index, array) {  
  if (array.length - 1 !== index){
    result += str + " ";
  } else {
    result += str + "!!!";
  }
});

forEach Example With All Callback Parameters

result =

"my "

"my"                 0                 strings

var strings = ["my", "forEach", "example"];

var result = "";
forEach(strings, function(str, index, array) {  
  if (array.length - 1 !== index){
    result += str + " ";
  } else {
    result += str + "!!!";
  }
});

forEach Example With All Callback Parameters

result =

"my forEach "

"forEach"           1                 strings

var strings = ["my", "forEach", "example"];

var result = "";
forEach(strings, function(str, index, array) {  
  if (array.length - 1 !== index){
    result += str + " ";
  } else {
    result += str + "!!!";
  }
});

forEach Example With All Callback Parameters

result =

"my forEach example!!!"

"example"          2                 strings

LIVE

CODE

forEach Code Along

By Elie Schoppik

forEach Code Along

  • 2,742