Different types of loops in JavaScript are forEach, for, for...of, and for...in

Can someone please help me understand the nuances between various types of loops? I am looking for resources that can explain these loops in terms of efficiency, speed, usability, and other factors.

How can I grasp the distinctions presented in the following code snippet?

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (let i = 0; i < digits.length; i++) {
  console.log(digits[i]);
}

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index of digits) {
  console.log(digits[index]);
}

Answer №1

Looping with for : One common method of looping through an array is by using the i variable as an index to access the elements in the letters array. For more information, refer to MDN Docs

var letters = ["a","b","c"];
for (let i = 0; i < letters.length; i++)
{
    console.log("Index : "+i, "Value : "+letters[i]);
}

The for...in Loop : This loop always iterates over the indices of an array. The variable i will hold the index value of each element during traversal. It can be useful when accessing element indices during iteration. For more details, visit MDN Docs

var letters = ["a","b","c"];
for (var i in letters)
{
    console.log("Index : "+i, "Value : "+letters[i]);
}

The for...of Loop : This loop directly accesses the values of an array during iteration. The variable i will hold the actual element value while traversing through the array. It's suitable when only the values of elements are needed. Learn more from MDN Docs

var letters = ["a","b","c"];
for (var i of letters)
{
    console.log(i);
}

Using forEach Loop : This loop executes a callback function on each element of an array. The callback receives parameters like currentValue, index of the currentValue, and the array itself. For more details, check out MDN Docs

var letters = ["a","b","c"];
letters.forEach(function(value, index, arr){
    console.log("Value : "+value, "Index : "+index, "Complete array : "+arr)
});

An Issue in Your Scenario : The code behaves correctly based on its logic. However, if your array elements match their indices, it can lead to confusion during interpretation.

In the for...in loop: index=0 corresponds to digits[0]=0, index=1 corresponds to digits[1]=1, and so forth.

In the for...of loop: index=0 (where variable index holds the value of digits[0]), the compiler interprets that value at index 0 is accessed in the d array. Thus, it returns the value at digits[0], and the same pattern continues for all elements.

Answer №2

The traditional approach:

for (let i = 0; i < digits.length; i++) {
  console.log(digits[i]);
}

This method solely depends on the condition involving i within the loop. If the condition i < digits.length is not met, the loop will terminate.

On the other hand, both alternative versions (using of and in) serve as iterators, meaning they will traverse through all the elements of the array without specifying the total number of items to iterate over.

However, there are distinctions between them:

  • The of keyword will iterate over the values in the array

  • The in keyword will iterate over the indices.

Typically, you would use them like this (example modified to highlight the difference):

const chars = ['A','B','C'];

for (const index in chars) {
  // index will be 0,1,2
  console.log(chars[index]);
}

It's preferable if you don't need the index explicitly:

const chars = ['A','B','C'];
for (const value of chars) {
  // value will be 'A','B','C'
  console.log(value);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When lines are added to a file in Node.js, the content is written in a haphazard sequence

I've encountered an issue with the code I wrote where the header line is not consistently at the top. It seems to randomly appear on the second or third line instead. I've tried troubleshooting multiple times without success, so any help would be ...

JavaScript Ajax request lags significantly in Internet Explorer, while it executes instantly in Firefox

So I have this jQuery .ajax() call set up to retrieve a List<string> of IP addresses from a specific subnet. I'm using a [WebMethod] on an .aspx page to handle the request and ASP.NET's JSON serializer to format the response for my Javascri ...

Encountered an issue with fs.open where a non-literal argument was used at index 0 while utilizing a url

Attempting to achieve something similar in TypeScript: window.open(`https://somelink/certificate/${regNumber}?registrationNumber=${type}`); where the values of regNumber and type are constantly changing. ESLint is reporting an issue: Received fs.open with ...

Click on the image to prompt the file upload dialog box to open

Is it possible to open the image upload file dialogue box when clicking the button tag? If so, how can I achieve this using PHP? while{ echo "<td><button><img src='".$cfet['productimage']."' width=&apos ...

Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0). To achieve this, I have developed a customized Camera Controller in three.js that simulates unique ...

How can I access the parent function within module.exports?

Hello, I am having issues with this code because I am unable to access checkIf in order to set its property LengthIs. When I log whether this is equal to module.exports, it returns false. Upon further inspection, I also checked what this was and it retur ...

Is the current version of NPM React-router too cutting-edge for your needs

When I use the command npm -v react-router on my React app, it shows version 6.9.0. However, when I check the npmjs page for react-router, the latest version available is 5.0.1. How can this discrepancy be explained? ...

How can I retrieve the most recent npm package version using code?

I'm in search of a method to retrieve the most up-to-date version number of an npm package. Is there an API available for indirect querying of npm, or is there a specific npm command that can be utilized programmatically? getNpmVersion('lodash&a ...

Type validation in TypeScript through cross-referencing variables

Can TypeScript be used to define a variable that determines the type of other variables? I want to simplify the process by only needing to check one variable, stateIndicator, which is dependent on other variables to infer their types. type A = {prop1: st ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...

The "Auto Load More" feature is only loading the first two pages when scrolling down

I have set up an auto load more feature that triggers on page scroll down. Although my jQuery/ajax code is functioning properly, it only loads the first 2 pages automatically as I scroll down. There are more pages/records available but the loading process ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

Toggle display of fields based on radio button selection in ASP.NET

I am new to C# asp.net and I am working on creating an online registration form. I am facing a challenge with the following issue. Could someone assist me, please? There are 5 fields in this problem: 1) Category: radio button with options for St ...

Issue encountered while attempting to launch Angular2 project

Having trouble running my Angular2 project, every time I try to use the ng serve command I get an error: Here is the link: https://i.sstatic.net/SYENX.png I've installed angular 2 using angular-cli with the following steps: 1. sudo npm install -g ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Is there a way to save the values of all input fields in a single container using local storage simultaneously?

Let's say I have the following structure: <div id="main"> <div id="wrapper"> <input/> <input/> <input/> </div> </div> My goal is to use localstorage to store the entire wrappe ...

Issue encountered in Typescript: callback functions are returning undefined value when called from a superclass

As a newcomer to TypeScript and Node.js, I decided to dive into something new by exploring Angular, Node, and Express. While attempting to practice good project structure practices in Express by breaking it down into smaller parts, I encountered an issue. ...