Using iterator functions in Javascript

JavascriptWeb DevelopmentFront End Technology

Other than Explicit iteration, Javascript provides a variety of iteration functions that you can use to iterate over arrays. Let's look at some of these functions −

ForEach Function

This function executes the function you pass to it for every object in the array. For example,

Example

let people = ['Harry', 'Martha', 'John', 'Sam']
people.forEach(person => console.log(person.toUpperCase()));

This will give the output −

Output

HARRY
MARTHA
JOHN
SAM

Map Function

This function executes the function you pass to it for every object in the array and creates a new array based on what you return to it. For example, 

Example

let people = ['Harry', 'Martha', 'John', 'Sam']
let upperCaseNames = people.map(person => person.toUpperCase())
console.log(upperCaseNames);

Output

This will give the output −

[ 'HARRY', 'MARTHA', 'JOHN', 'SAM' ]

Filter Function

This function executes the function you pass to it for every object in the array and creates a new array based on the values that return a truthy value. For example, 

Example

let people = ['Harry', 'Martha', 'John', 'Sam']
console.log(people.filter(person => person[0] === 'H'));

This will give the output −

Output

['Harry']

There are many other such functions like reduce, every, some, etc that you can read more about on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

raja
Published on 27-Jun-2018 06:21:36
Advertisements