DEV Community

zain ul abdin
zain ul abdin

Posted on

3

3 Types of for Loops in JavaScript

We all know and love the classic for loop, but did you know that JavaScript has a few other powerful for loop options up its sleeve?

1) for/in: This one is very useful to iterate over the keys of an object and manipulating object properties.

Example:

const obj = {name: "JavaScript", type: "Language"};
for (let key in obj) {
    console.log(key); // outputs "name" and "type"
}
Enter fullscreen mode Exit fullscreen mode

2) for/of: This one is optimal when your focus is on the values rather than the keys or indices of iterable objects, such as arrays or strings.

Example:

const arr = ["JavaScript", "is", "versatile"];

for (let value of arr) {

  console.log(value);

}
Enter fullscreen mode Exit fullscreen mode

3) forEach: This one is a gem, as it offers convenience and readability, helping you iterate over arrays with minimal syntax, so you can focus on the logic within the loop rather than the iteration process itself.

Example:

const arr = ["JavaScript", "is", "versatile"];

arr.forEach(value => console.log(value));
Enter fullscreen mode Exit fullscreen mode

Which of these is your favorite?

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (2)

Collapse
 
john_phillips profile image
John

I’m all about that forEach loop. It’s clean, easy to read, and you don’t have to worry about messing up the index or anything. Plus, it just feels more modern and JavaScript-y, you know?

Collapse
 
__525a profile image
Александр Чембулатов

Try to process async function inside foreach )). You will be surprised.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay