4 ways loop through items in array in javascript

Photo by Srinivas JD on Unsplash

This is a brief introduction of 4 ways loop through items in array.

1: for

This is the simplest way. You can modify the i++ to skip some of the array items. eg i+=2 to skip all even items.

let arr=[1,2,3,4] 
for(i = 0; i < arr.length; i++) {
console.log(arr[i]); //output:1 2 3 4
}

2: for-in (not recommend)

This method will give you the index(key) of array as string.

You may need to access the item by arr[index].

let arr=[1,2,3,4] 
for(let index in arr) {
console.log(index); //output:0 1 2 3
console.log(typeof index) //output: string
}

3: forEach

You can pass a function to forEach :value=>{…}

If you want to modify the items you can pass a function like this: (value,index,array)=>{...} then access the item by array[index]

let arr=[1,2,3,4] 
arr.forEach(value => console.log(value)); //output:1 2 3 4
arr.forEach((value,index,array) => array[index]=++value);
console.log(arr) //output:[2 3 4 5]

You may want to use for-of rather than forEach if it involves async/await, to learn more, please read my story about async/await with forEach

4: for-of

Similar to for-in, but this method will give you the value of array item.

let arr=[1,2,3,4] 
for(let value of arr) {
console.log(index); //output:1 2 3 4
}

--

--

--

Hi, I am interested in IT field including front-end, back-end, database, networking.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Build your first React App

//platform.twitter.com/widgets.js from Twitter https://twitter.com/UKCareGuide

Day 11: Intro To JavaScript

Custom Partials with Lerna and conventional-changelog

Infinite Scrolling

The MVP of Computational Integrity

JavaScript Algorithms. Chunk arrays

Iframe Performance Part 2: The Good News

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Frankie

Frankie

Hi, I am interested in IT field including front-end, back-end, database, networking.

More from Medium

5 Ways to Clean up your JavaScript / ReactJS Code

The Junior Developer Journey (02 May 2022)

Deleting Elements from Arrays in JS

CleverTap Javas Hackathon Experience