DEV Community

loading...

What are JavaScript loops?

uma profile image Uma Updated on ・6 min read

In this article, we will discuss a very important part of javaScript: loops, which means doing things repeatedly. Loops allow us to repeat certain chunks of code using some conditions. If we have to print something a certain number of times, sum all the numbers in an array, or list all the keys/values from an object, we can do so by using loops. There are different types of loops:

for loop:

It loops through a block of code until the counter reaches a specified number.
syntax :

for([initial expression] [condition] [increment expression]) {
//statement 
}

//example of a for loop

for(let i = 1; i <= 10; i++) {
    console.log(Hello, my name is Uma!, i)
}
>Hello, my name is Uma! 1
>Hello, my name is Uma! 2
>Hello, my name is Uma! 3
>Hello, my name is Uma! 4
>Hello, my name is Uma! 5
>Hello, my name is Uma! 6
>Hello, my name is Uma! 7
>Hello, my name is Uma! 8
>Hello, my name is Uma! 9
>Hello, my name is Uma! 10

Enter fullscreen mode Exit fullscreen mode

Above we set the counter variable i to 1, then conditionally check if i is less than or equal to 10 and increment i each time until the condition is met. As we can see, it printed out the string 10 times, and each time it printed, the counter was incremented by 1.

One important part to discuss here is the idea of an Infinite loop. This is something we never want to encounter because an infinite loop never ends and will end up crashing your program. Which of course you never want to happen. Have a look at an example below:

for(let i = 1; i !==20; i+=2) {
    console.log(i)
}

Enter fullscreen mode Exit fullscreen mode

What is wrong with the above code snippet? Yes, you guessed it right- the condition. That condition will never be met: by incrementing by 2 each time from the starting counter value of 1, it will only print out odd numbers, which means the counter i variable will never be set to the value of 20, so it will keep running until your program crashes(oops!). It's recommended to not use == or !== in a for loop, instead use >= or <=, which will prevent an infinite loop even if the condition is not met.

Can we use for loops with Arrays and Strings?
The answer is yes. Let’s look at a few examples of using a for loop with arrays and strings below:

const studentsName = [Uma, Collin, Jordan, Henry, Wills]

for(let i = 0; i < studentsName.length;  i++) {
     console.log(studentsName[i])
 }
>Uma
>Collin
>Jordan
>Henry
>Wills

Enter fullscreen mode Exit fullscreen mode

Let's take a look at another example that has objects inside an array.

const myFamily = [
{
  Name: Umesh,
  Age: 36
},
{
  Name: Uma,
  Age: 35
},
{
   Name: Aiden,
   Age: 4
}
]

for(let i = 0; i < myFamily.length;  i++) {
   let familyMember = myFamily[i]   //this has to be inside the loop to access one object at a time
     console.log(`${familyMember.name} is ${familyMember.age} years old.`)
 }
>Umesh is 36 years old.
>Uma is 35 years old.
>Aiden is 4 years old.

Enter fullscreen mode Exit fullscreen mode

Now let's take a look at a string. This time we will use decrement(--) instead of increment(++):

const greet = Hello!
for(let i = greet.length - 1; i >= 0; i--) {
   console.log(i, greet[i].toUpperCase())
}
>5, !
>4, O
>3, L
>2, L
>1, E
>0, H

Enter fullscreen mode Exit fullscreen mode

Pretty straight forward right?

while loop:

A while loop continues to run as long as its test condition is true.
Syntax:

while(condition) {  //condition needs to be true
  //statement   -need to make it false somehow, otherwise, it will turn into an infinite loop
}
Enter fullscreen mode Exit fullscreen mode

Let's take a look at a simple While Loop example:

let age = 8

while(age < 18) {
      console.log("your age is less than 18, you can't have a drink right now!") 
      age++
   }
   console.log("You are now over 18, enjoy your first drink. Cheers!!")

>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>your age is less than 18, you can't have a drink right now!
>You are now over 18, enjoy your first drink. Cheers!!

Enter fullscreen mode Exit fullscreen mode

Here is another example of a While loop:


const target = Math.floor(Math.random()* 10)
let yourGuess = Math.floor(Math.random()* 10)

while(yourGuess !== target) {
    console.log('try again') 
    yourGuess = Math.floor(Math.random() * 10)
  }

console.log(`Target: ${target} yourGuess: ${yourGuess}`) 
console.log('Congrats you win!')

> try again
> Target: 2 yourGuess: 2
> Congrats you win!

Enter fullscreen mode Exit fullscreen mode

for...of loop:

for...of is an easy way of iterating over arrays or other iterable objects.
Syntax:

 for( variable of iterable) {
       statement
  }

Enter fullscreen mode Exit fullscreen mode

We can use the same example from the for loop with arrays to see the difference between these two methods. With a for loop, to access an element from an array we had to do this:

const studentsName = [Uma, Collin, Jordan, Henry, Wills]

 for(let i = 0; i < studentsName.length;  i++) {
     console.log(studentsName[i])
 }
>Uma
>Collin
>Jordan
>Henry
>Wills

Enter fullscreen mode Exit fullscreen mode

Now with a for...of loop we can simply do like so:

const studentsName = [Uma, Collin, Jordan, Henry, Wills]

for(let name of studentsName ) {
     console.log(name)
 }
>Uma
>Collin
>Jordan
>Henry
>Wills

Enter fullscreen mode Exit fullscreen mode

BOOM. How cool was that? We can use the same logic with a String.

const word = welcome!

for(let char of word) {
   console.log(char)
}
> w
> e
> l
> c
> o
> m
> e
> !

Enter fullscreen mode Exit fullscreen mode

for...of is a great fit most of the time but where we need to use indexes, it’s not recommended to use for..of. In that case, a for loop is better to use. For example, if we have two arrays:

const words1 = [orange, peanut, strawberry]
const words2 = [juice, butter, jam]

Enter fullscreen mode Exit fullscreen mode

To print the corresponding indexes of “orange juice”, “peanut butter” and “strawberry jam”, we need to have access to the indexes which is not possible with the for...of loop but we can easily solve it with a for loop like so:

for(let i = 0; i < words1.length; i++) {
    console.log(`${words1[i]  ${words2[i]}`)
}
> orange juice
> peanut butter
> strawberry jam

Enter fullscreen mode Exit fullscreen mode

Neat!!

Now the question is can we use for...of with an object?
The answer is yes but it's not as straightforward as with an array. Objects are not iterable. So how can we use a for...of loop with an object? Here is an example:

const progressReportOfAiden = {
    math: 10,
    science: 9.5,
    english: 9.5,
    art: 9,
    history: 8,
    social: 8.5,
    nepali: 8
}

// to print out only subject names we can do so by:
// in Object.keys Object needs to be capitalized. 

for(let subject of Object.keys(progressReportOfAiden) {
    console.log(subject)
}
> math
> science
> english
> art
> history
> social
> nepali

Enter fullscreen mode Exit fullscreen mode

If you are not familiar with Object.keys, have a look at this piece of documentation. Similarly, to access only values use Object.values instead of Object.keys.

for...in loop:

for...in loops over keys in objects, whereas in for...of we had to use Object.keys to access keys to loop over. This is the easier way to loop over keys.
Syntax:

for( variable in object) {
   statement
}

Enter fullscreen mode Exit fullscreen mode

Now let’s use a for...in loop in the above for...of loop example:

const progressReportOfAiden = {
    math: 10,
    science: 9.5,
    english: 9.5,
    art: 9,
    history: 8,
    social: 8.5,
    nepali: 8
}

// to print out only subject names we can do it so by:

for(let subject in progressReportOfAiden) {
    console.log(subject)
}
> math
> science
> english
> art
> history
> social
> nepali

// to access values just console.log(progressReportOfAiden[subjects])

Enter fullscreen mode Exit fullscreen mode

Ahhh much easier... And that's all for javascript loops. Thank you for reading.
Happy coding.

Discussion (0)

pic
Editor guide