DEV Community

Sri Sai Jyothi
Sri Sai Jyothi

Posted on

6

Describing For loops in JavaScript

1. The Standard For loop

let numbers = [10,20,30];
for(i = 0; i < a.length; i++ ){
  console.log(numbers[i]);
}

👉 We can use break, continue, and return inside of the standard for loop.

2. forEach Loop

let numbers = [1,2,3];
numbers.forEach(function(value){
  console.log(value);
}
  • Now, we'll get exactly as the same output as in case of the standard for-loop.

👉 We CANNOT use break or continue inside forEach loop.

👉 We can use the return keyword (forEach is anyway a function so it doesn't make any difference to use it)

3. For-in Loop

👉 It is used for looping over object properties.

  • What happens if we loop through an array?
// Looping through Objects
let obj = {a:10, b:20, c:30};
for(let prop in obj){
console.log(prop) //0
console.log(typeof(prop)) //string
}

//Looping through an array
let numbers = [10,20,30];
for(let index in numbers){
console.log(index) //0
console.log(typeof(index)) // stringâť—
}

4. For-Of Loop

👉 Use for-of to loop over itterables like arrays.

let numbers = [10,20,30];
for(let index of numbers){
console.log(index) //0
console.log(typeof(index)) // numberâť—
}

Summary

  1. đź“ť The main difference between for and forEach is the use of break, continue, and return
  2. đź“ť The main difference between for-in and for-of is the former is used to iterate over Object properties and the latter is for iterables like arrays.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (2)

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei •

Thanks for the summary of the "for" loops.

Collapse
 
vssj01 profile image
Sri Sai Jyothi •

Thank you for reading :)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

đź‘‹ Kindness is contagious

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

Okay