How to loop through an array in JavaScript?

Today we will look at couple of ways to loop through an array in JavaScript. Let's use this social array for iteration.

Feel free to write in your favorite editor or on the browser console.


let social = ["twitter", "instagram", "facebook", "linkedin", "snapchat"];
// Using for loop
for(var x = 0; x < social.length; x++){
// Using forEach
social.forEach((channel) => console.log(channel))
//Using for-of
for(const channel of social){
// Using map => console.log(channel));

Full Transcript

Hi, and welcome to JavaScript series. Today. We will look at a couple of ways to loop through an array in JavaScript. Let's use the social array for iteration. It contains the name of few social channels. I'm using Chrome snippets in my browser to write the code, but feel free to write it in your favorite editor or on the browser console. We have this array containing the names of social channels. We declare it and add the values, Twitter, Instagram, Facebook, LinkedIn, and Snapchat. Now our goal is to loop through every element in the social array and print that element. The first approach is to use for loop in JavaScript. The way to use it is by writing for var x=0, because you would like to iterate from 0th index and go until the last element of the array, which can be determined using length property of the social array, increment the index each time by one,

so we will use console.log() to print on the console, each element at index x from the social array. Let's run the code and you can see it logs every element in this array. Now, the second approach is to use foreach() method available on arrays. To use foreach, you need to pass a function as an argument, which will be executed on each element of this array. One of the parameters of this function is the current element in the array. So we pass through this function an argument channel, which is nothing but the current social channel. When this function executes, it logs every channel on the console. We'll run it again, and the same result. Now the third approach would be to use for-of, which gives you the direct access to the element in an iterable. Unlike the simple for loop, we looked at the for-of loop came from ES6 specification. Here, you simply need to declare a variable channel, which can be const because you are not modifying the channel variable. The keyword of is for the array social. So all we are saying here is for every channel of social array, log the channel value on the console and that's it. Let's run it again. And we got the same results. So if you simply want to iterate through an array to access its elements, you can use any of these loops to do so. That's all I wanted to cover in this video. Thanks for watching. And I'll see you in the next video.