Topic Overview and Actualization

Welcome to this interesting lesson! We're going to explore JavaScript array methods, specifically: forEach(), map(), filter(), reduce(), and find().

Understanding the Role of Array Methods

JavaScript arrays can store multiple values. Array methods enable us to perform operations such as modifying or searching array elements. To call array methods, you use dot-notation on the array. For example: arrayVar.arrayMethod(func).

Array Methods accept a function as a parameter either using the => operator or passing the function name. For example:

arrayVar.arrayMethod( (functionParameters) => /* function code */ )
arrayVar.arrayMethod(myFunction)
Looping Through Data with forEach()

To inspect each element in an array, we use the forEach() method, which runs a function on each array element.

const stars = ['Sirius', 'Vega', 'Rigel', 'Polaris'];
stars.forEach((star) => {
    console.log(star); // prints star names one by one
});

/* Prints
Sirius
Vega
Rigel
Polaris
*/

stars.forEach((star, index) => {
    console.log(star, index); // prints star names along with their indices in the array
});

/* Prints
Sirius 0
Vega 1
Rigel 2
Polaris 3
*/

The forEach() method accepts a function as a parameter, using the => operator, and runs the function on each element of the array. If we just want the value of each element in the array, we specify the input to our function as just (star). If we want the value of each element and its index, we specify the input as (star, index).

Transforming Data with map()

The map() method transforms data and creates a new array based on the results of a function.

Just like forEach(), map takes in a function as an input. map() returns an array where each element is the value returned by calling our function on that element.

const stars = ['Sirius', 'Vega', 'Rigel', 'Polaris'];
const brightStars = stars.map((star) => {
    return star + ' is very bright!';
});
console.log(brightStars); // prints star names with added info
// Prints ['Sirius is very bright!', 'Vega is very bright!', 'Rigel is very bright!', 'Polaris is very bright!']
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal