Loading...

Loops in JavaScript: for and while loops

Loops in JavaScript: for and while loops

In the previous blog post, you learned about arrays in JavaScript, why they are important and what’s their utility. I had left you with a question.

What if you had 20 individuals, with their names and age in an array and you wanted to check if they were eligible to drive or not?

20 Individuals
20 Individuals

To do this, one approach would be to index each individual separately and check if their age is more than 18.

This approach is time-consuming and not very scalable. What if you had 100 or 1000 individuals?

This is where loops in JavaScript come in. If you want to code alongside, fire up your own online compiler via codedamn playgrounds! And you can access all the code in the article here.

What are Loops?

In the problem statement, while the individuals are different, the task of checking if the age is equal to or more than 18 for each individual, is exactly the same and would look something like:

if (age >= 18) { console.log("Individual is eligible to drive.") }
Code language: JavaScript (javascript)

If you could repeat this block of code for every individual, you would be able to solve the task. Loops help you do just that! They will run this block of code for all the objects in the array without you having to index an individual separately. There are different types of loops available in JavaScript. In this article, we will look at the for and while loops.

for Loop

A for loop will help you do a certain task (read, repeat a block of code) n times. In other words, if you know you want to run a piece of code 20 times, you would do it with the for loop. But for loop is dumb. You need to tell it:

  • Where to start
  • When to stop
  • How many times to run between start and stop, and
  • What to do
Syntax of for Loop
Syntax of for Loop

From the arrays block, recall:

  • The position of the first element is denoted by 0. This is the start
  • You index an element with square brackets, for example: individuals[0] will return the details for Aaron
  • Length of the array can be accessed by array.length. This is the stop.

We need to run the if code block for every element in the array from index 0 to index 19 (length is 20).

for loop in JavaScript
Click here for the Code

Point 1: You start at index 0. To do that, you initialize a new variable i with the value 0.

Point 2: You want to run the loop for all the individuals in the array. Therefore, you would always want i to be less than or equal to the last position of the array. The length of the array is 20! Therefore, with this stop condition we make sure that i will never be greater than 19, which is the index of the last Object in the array.

Point 3: Since you want to check for every element in the array, you increment i by 1.

TL;DR: Whatever is inside the for loop, run it 20 times beginning from 0 (starting value of i) to 19 (ending value of i) and increment i by 1.

Inside for, the code is accessing the age property of an Object inside the array individuals, and checking to see if it is greater than or equal to 18! If it is it prints it out on the console. If you do not understand any part of this, I am adding links to some of my previous blogs which go through these concepts in detail:

  • Object Data Type in JavaScript
  • Arrays in JavaScript
  • if….else in JavaScript

Try out a simple task now:

Print the numbers from 10 to 30 (including 30), thar are divisible by 2.

Once you do it yourself, check the code below for a solution:

Even Numbers between 10 and 30
Click here for the Code

Carefully check the code. i starts from 10, and ends at 30 (i < 31). To get only even numbers, we increment i by 2! (i += 2).

The output is all the even numbers between 10 & 30.

To understand the flow better, check out the table below that shows what happens at each value of i:

IterationVariablei < 31OutputNew Value of i
1i=10true10i += 2
i = 12
2i=12true12i += 2
i = 14
3i=14true14i += 2
i = 16
4i=16true16i += 2
i = 18
5i=18true18i += 2
i = 20
11i=30true30i += 2
i = 32
12i=32falseLoop Breaks!

The loop breaks and stops executing the code inside it as soon as i becomes greater than 31!

You have gained a solid understanding of for loops! As an exercise, attempt to print the name of all the individuals at the odd position in the array in capital letters!

while Loop

A while loop does the same job as a for loop, but it is used when we do not know the number of iterations we have to run! In the example for the for loop when printing even numbers, we knew that the upper limit is 30 and we don’t care about the values beyond that. What if, instead of defining 30 in the code, it was a value defined by the user? A user could give the value as 100, in which case your task becomes printing all even numbers between 10 and 100!

In such situations, where you cannot determine at the time of writing code, the number of iterations needed, you should use a while loop.

Syntax for while loop:

while (condition is true) { // Code to run }
Code language: JavaScript (javascript)

Let’s check the code for printing even values between 10 and 100:

while loop in JavaScript
Click here to get the Code

TL;DR: Till the time i is less than 101, output i and increment its value by 2!

The user input could be anything that you don’t know. In this case, if you change the userInput variable to 200, you do not have to make any change in the while loop and it will still run as expected.

A major difference from the for loop is that the increment for i is done inside the body of while loop. If you forget to do this, you will be stuck in an infinite loop and the output will keep on printing 10! Try it out, it is fun!

The iteration table is the same for while loop as was for the for loop. I am adding it here for your reference!

IterationVariablei < userInputOutputNew Value of i
1i=10true10i += 2
i = 12
2i=12true12i += 2
i = 14
3i=14true14i += 2
i = 16
4i=16true16i += 2
i = 18
5i=18true18i += 2
i = 20
46i=100true100i += 2
i = 102
47i=102falseLoop Breaks!

break & continue in JavaScript Loops

break Statement

What if in the code below, as soon as i = 16, you want to stop. You do not want to print any further. How would you do it? And you cannot change 31 to 17!

for (let i = 10; i < 31; i += 2) { console.log(i) }
Code language: JavaScript (javascript)

It is simple! JavaScript has a reserved keyword break. Whenever break is added inside a loop, JavaScript will stop any further execution of the loop. It is best explained with an example.

Click here to get the Code

Notice how the values 18, 20, 22, …….., 30 are never printed! As soon as i equals 16, the execution stops because the break statement tells JavaScript to exit out of the loop! What if there was no if condition?

JS would start the loop, and print 10. Immediately after that it would encounter the break statement and exit the loop. So only 10 will be printed!

Click here to get the Code

continue Statement

In the example above, what if the problem was to print all the even numbers between 10 and 30, except 16?

continue statement will do just that! Whenever for an iteration, a continue statement is available, any code after the statement will be completely ignored and the loop will move to the next iteration!

Click here to get the Code

The loop printed: 10, 12, and 14. But as soon as i was equal to 16, JavaScript completely skipped the code after that. In this case it skipped:

console.log(i) // i===16
Code language: JavaScript (javascript)

And it directly moved to the next iteration of printing 18!

Conclusion

In this blog, you learned about the for and while loops with detailed examples! You also experimented with the continue and break statements. Loops helped you repeat a block of code again and again! In this case, it was conditional statements.

Coming up are functions in JavaScript, one of the most crucial concepts in JavaScript that you will use extensively in your programming career!

Stay tuned and till then, practice, practice and practice, on codedamn playgrounds!

Sharing is caring

Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far