DEV Community

Cover image for JavaScript For Loops Explained For Beginners
Tia Eastwood
Tia Eastwood

Posted on • Updated on • Originally published at tiaeastwood.com

JavaScript For Loops Explained For Beginners

The for loop is one of the things you will come across quite early on in your JavaScript journey.
The first time I saw one, I struggled to understand what it all meant, so don't worry if you feel the same! Hopefully this will help you to understand how and why you would use a for loop:

Let's have a look at an example of a typical for loop:

for (let i = 0; i < array.length; i++)
Enter fullscreen mode Exit fullscreen mode

A common reason for why you might need to use a for loop, would be to iterate through an array of data; this means to check each piece of data in the array. Now let's break it down:

Setting up the for loop

for
Enter fullscreen mode Exit fullscreen mode

We use the word for to indicate that we are about to use a for loop. Then the mechanics of our for loop will go between two brackets ().

The Iterator

let i = 0
Enter fullscreen mode Exit fullscreen mode

You are declaring a variable called i by using the let variable keyword. This is your iterator. In this case, i = 0 because 0 is the first index of an array, and we want to start from the beginning. You don't have to call it i by the way! You can call it what you want, as long as it abides by JavaScript variable naming rules. Most people call it i though because it stands for iterator and it has become the convention.

The Condition

i < array.length
Enter fullscreen mode Exit fullscreen mode

This tells our for loop when it should run and when to stop. In this case, the loop will continue running as long as the value of i is less than the array length. (The array length is the number of items in the array). With this instruction, the loop will check every item in the length of the array and then stop. Without this, our code would result in an infinite loop because it wouldn't know when to stop. You do not want an infinite loop, as it could freeze up or crash the browser.

The Incrementor

i++
Enter fullscreen mode Exit fullscreen mode

This tells our loop to increment by 1 (i++ is the same as i + 1). This means that in the next loop, it will move on to check the next item in the array; it will move forward by 1 index position. If you wanted it to check every other item in the array instead, you could change that to i + 2, so the incrementor will move forward by 2 index positions. There is also a way to go backwards too, can you think how we would do that?


Using a for loop in a function

Now you'll see a for loop in action within a function!
Let's say I wanted to return only the even numbers from this array called numArray...

const numArray = [1, 6, 9, 12, 18, 23, 47, 52];
let evenNums = []; 

function findEvenNums(numArray) {
  for (let i = 0; i < numArray.length; i++) { 
    if (numArray[i] % 2 === 0) { 
      evenNums.push(numArray[i]); 
    }
  }
  return evenNums; 
}

console.log(findEvenNums(numArray)); 
Enter fullscreen mode Exit fullscreen mode

Ok so let's talk about what we're looking at here:

  • In order to check each number, I used a for loop to iterate through the array. Starting from the beginning (let i = 0), the for loop runs until the array ends (i < numArray.length) and will increment by 1 each time (i++) to make sure it checks every number.
  • I then used an if statement which is something you will often see used with a for loop.
  • The if statement checks if numArray[i] (which is the current index of numArray) meets a certain condition (in this case, if the number is divisible by 2 with no remainder AKA an even number).
  • If if meets that condition, then the number gets pushed onto my evenNums array.
  • The loop repeats this process, iterating through each number, before it reaches the end of the array.
  • Once the loop completes and exits the cycle, our function will return the evenNums array. Your return must be outside the loop is you want the loop to complete it's full cycle.
  • Finally, I call the function (within a console.log() so I can see the result in the console).

Time to play!

Now we've analysed that function, try having a play around with it! I have created a fiddle where you can play with the above code on JS Fiddle, or you could put it into your own preferred code editor.

Try changing certain things like adding different numbers to the array, or change certain parts of the for loop or the if statement. See how it affects the function!

I also highly recommend trying to write your own functions to solve problems using for loops. CodeWars is a great place to practice this!


I hope you found this helpful in understanding how for loops work! If you have any questions, you can always tweet me @TiaEastwood and I'll do my best to help!
Bye for now!

Top comments (4)

Collapse
 
h1manshu01 profile image
Himanshu Sharma

You made it very simple to understand. I wish u to write an article about async await and promises.

Collapse
 
tiaeastwood profile image
Tia Eastwood

Thank you for the suggestion!

Collapse
 
tiaeastwood profile image
Tia Eastwood

Thank you for the feedback and the tips!