JavaScript ‘For’ Loop

Suneet Agrawal
2 min readMay 17, 2023

Loops are an essential part of any programming language, and JavaScript is no exception. One of the most common loops used in JavaScript is the for loop. In this blog, we will focus on the for loop in JavaScript and how it can be used to iterate over an array or object.

This post was originally posted at https://agrawalsuneet.github.io/blogs/javascript-for-loop/ and later reposted on Medium.

Loops are an essential part of any programming language, and JavaScript is no exception. One of the most common loops used in JavaScript is the for loop. In this blog, we will focus on the for loop in JavaScript and how it can be used to iterate over an array or object.

What is a for loop?

A for loop is a programming construct used to repeat a section of code for a specified number of times. The loop consists of three parts:

  • Initialization
  • Condition
  • Increment/Decrement

The syntax for a for loop in JavaScript is as follows:

for (initialization; condition; increment/decrement) {
// code to be executed
}

Let’s break down each part of the for loop in more detail.

  • Initialization: This is the initial step where we set a variable to a specific value. This part is executed only once before the loop starts.
  • Condition: This is the condition that needs to be met in order for the loop to continue running. If the condition is true, the loop will continue running; if the condition is false, the loop will terminate.
  • Increment/Decrement: This is the step that is executed after each iteration of the loop. It is used to change the value of the variable used in the condition.

For Loop Example

The code block to be executed is enclosed within curly braces {}. This is where you put the code that you want to repeat.

for (let i = 0; i < 10; i++) {
console.log(i);
}

In this example, we are using the for loop to log the numbers from 0 to 9 in the console.

  • The initialization statement sets the value of the variable i to 0.
  • The condition statement checks if i is less than 10. If it is true, the loop will continue. If it is false, the loop will end.
  • The increment statement increments the value of i by 1 after each iteration.

For Loop for Arrays

The for loop can also be used to iterate through arrays in JavaScript.

Please continue reading at https://agrawalsuneet.github.io/blogs/javascript-for-loop/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--