Array Methods
Introduction to array methods that use functions.
In this lesson, we’ll discuss array methods and their convenient usages.
Introduction
Methods of an object are property names assigned to functions. These methods can be invoked to execute the function. Now, let’s take a look at different methods.
forEach
method
forEach
method is used to iterate an array in loops. Let’s dig deeper into this method.
Syntax of forEach
method
The syntax of the forEach
method is as follows.
arr.forEach(<function>);
The forEach
method above takes, as an argument, a function invoked for each element in the array. The function to be passed is given arguments in the following order, by the forEach
method.
function callbackfn(value: any, index: number, array: any[])
For each element, the callbackfn
is passed with the value of the element as the first argument, followed by the index of the element as the second argument, and lastly the array itself as the third argument. We may write the callbackfn
function to take 0 to 3 arguments.
Look at a couple of examples.
var arr = [10, 20, 30, 40, 50]; // initialise an array and assign to arrarr.forEach((val, ind, array) => { // arrow function to print argumentsconsole.log("Value:", val, " Index:", ind, " arr:",array); // print values});console.log(arr); // print array assigned to arr
In the above example, we call the forEach
method for the array assigned to arr
variable. To the forEach
method, we pass an arrow function which takes three arguments: val
, ind
, ...