DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Why React Router 7 Is a Game-Changer for React Developers

Trending

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  1. DZone
  2. Data Engineering
  3. Data
  4. For Loops in JavaScript: Native, forEach, and For-of

For Loops in JavaScript: Native, forEach, and For-of

By 
Peter Connelly user avatar
Peter Connelly
·
Mar. 02, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
11.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we're going to walk through the many different ways to loop through arrays in JavaScript, from the native approach many will be familiar with, to more recent (and readable) methods introduced in ES6 and later. 

Native For-Loop

JavaScript
 




xxxxxxxxxx
1


 
1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2
 
          
3
for(let i = 0; i < myArray.length; i++) {
4
    const currElem = myArray[i];
5
  
6
    console.log(`At index ${i}, our element is: ${currElem}`);
7
}



If you're new to programming, this might be a whole new concept. (If so, welcome! We're excited to have you. For those of you who've seen this more than a few times, feel free to skip to a later section.) In the above code block, we're first creating an array containing a "Hello, World!" message. 

Next, we're starting our for-loop. For-loops are defined by two sections, a header, where we specify how the loop will run, and the body, where we define what will happen at each iteration of our loop. The head of a for-loop contains three sections. The first defines a value, often a single letter, like i, that we want to start indexing our array at. The second defines a condition that will terminate our for-loop. The third performs an operation on i to move it to the next element in the array. 

In this case, i is 0, our terminating condition is i < 7 (the length of our array), and we add 1 to i to move it to the next index in our array. This tells our program that we want to look at each element in our array, starting at 0 (our first index) and ending at 6 (our last index).  

You may also like: Iteration Over Java Collections With High Performance.

In the body of our for-loop, we grab the element at i, assign it to a variable, currElem, and then print the index and the value of currElem to the console. Our output for this will be: 

Plain Text
 




x





1
At index 0, our element is: Hello,
2
At index 1, our element is: world!
3
At index 2, our element is: It's
4
At index 3, our element is: nice
5
At index 4, our element is: to
6
At index 5, our element is: meet
7
At index 6, our element is: you!



forEach Loop

Among the many helpful array methods introduced in ES6 is forEach. forEach takes a callback function as a parameter. The callback then takes a variable representing an individual element in an array as a parameter. Inside the body of the callback, we can create custom logic to perform an operation with or on each individual element of the array. 

Note: forEach does not return a new array of elements. If you mutate the element within the callback function, every element in the array will be mutated. (Take a look at map if you're looking to maintain state). 

Let's see a simple implementation of the method with an anonymous callback function as our argument: 

JavaScript
 




x




1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2
 
          
3
// the callback doesn't have to be an arrow function. You could 
4
// achieve the same result with the 'function' keyword
5
myArray.forEach(elem => {
6
    console.log(`Current element: ${elem}`); 
7
}



You can also use a predefined function as the callback, like this: 

JavaScript
 




xxxxxxxxxx
1


 
1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2
 
          
3
const printSomething = varToPrint => {
4
    console.log(`Current element: ${varToPrint}` 
5
}
6
                
7
myArray.forEach(printSomething)



Both of these implementations will result in a similar output to the one we had with our native for-loop: 

Plain Text
 




xxxxxxxxxx
1


 
1
Current element: Hello,
2
Current element: world!
3
Current element: It's
4
Current element: nice
5
Current element: to
6
Current element: meet
7
Current element: you!



If you need the index of the current element in the array, you can just add a second parameter to the callback function, like: 

JavaScript
 




xxxxxxxxxx
1


 
1
arr.forEach((elem, i) => {
2
  // some logic cooler than printing things out 
3
}



Here, i is the current index of the array, while elem is the current value at that index. 

For-of Loop

For those coming from a Java background, JavaScript's for-of loop will be pretty similar syntactically to an enhanced for-loop (though it's not so "enhanced" when you look at its actual performance). To me, for-of is the most readable option that the language offers:

JavaScript
 




x


 
1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2
 
          
3
for(const elem of myArray) {
4
    console.log(`Current element: ${elem}`);
5
}



The syntax here is pretty straightforward. In the first half of the header, we declare a variable that represents an individual element in our array. We then use the of keyword followed by the array that we want to iterate through: "For every element of this array, do something." (The only implementation that would be more readable would be if in could replace of (*cough* Python), but objects own that keyword for loops in JavaScript, and if a preposition is the only thing I can complain about here, my life's not that hard.)


Further Reading

  • An Introduction to JavaScript/ES6 Arrow Functions/
  • JS Array From an Array-Like Object
  • Debug JavaScript in Production With Source Maps


JavaScript Data structure Element

Opinions expressed by DZone contributors are their own.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Why React Router 7 Is a Game-Changer for React Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!