Empowering you to understand your world

A Guide To ‘For’ Loops In JavaScript

‘For’ Loop Basics

In this article, I will teach you how to use ‘for’ loops in JavaScript. ‘For’ loops enable you to set a variable to increment or decrement, how much you want them to increment or decrement each time the loop runs, and at which point the loop must stop (usually when the variable specified above adds up or decreases to a certain number).

You can try out the code below in a JavaScript code interpreter.

Example of an incremental ‘for’ loop:

for (i = 0; i < 10; i++) {
  console.log("This text will be printed to the browser console 10 times.");
}

i = 0 initializes the variable at a value of 0, i < 10 instructs the computer that the loop must be executed ten times, and i++ makes the computer add 1 to i every time the code executes. It will do this until equals 10.

Example of a decremental for loop:

for (i = 10; i > 0; i--) {
  console.log("This text will be printed to the browser console 10 times. It counts down from 10 to 0.");
}

i– simply instructs the computer to decrement by 1 every time the loop runs. It will stop when i is equal to 0, which is indicated by the use of the i > 0 instruction.

You can adjust the counter by using += instead of ++ as shown below.

for (i = 0; i < 10; i+=5) {
  console.log("This text will be printed to the browser console 2 times.");
}

i+=5 adds 5 to i every time the loop is run, unlike i++ which adds 1 to it.

If you’d like to decrement by a number of your choice, you can use -= instead of += as shown below:

for (i = 10; i > 0; i-=5) {
  console.log(This text will be printed to the browser console 2 times.”); //This code decrements by 5 until i = 0.
}

You can change the 5 to any number you like, as well as any of the other numbers shown above, just be careful not to crash your browser with an infinite loop!

Uses Of For Loops

Examples Of For Loop Usage

//Print array contents using a for loop

var myArray = ["Peach", "Orange", "Apple", "Avocado", "Beets", "Celery", "Carrot", "Kale", "Potato", "Lettuce"];

for (i = 0; i < myArray.length; i++) {
  console.log(myArray[i]); //This prints all the fruits and vegetables in the array.
}

myArray.length is equal to the length of the array, therefore, the loop will stop when i = 10. The array.length method makes it easy for you to stop your loops at the end of your arrays, even if the length of your array changes.

Leave a Reply
Subscribe to our newsletter
Get notified when new content is published