DEV Community

Randy Rivera
Randy Rivera

Posted on

Loops

Iterate with JavaScript While Loops

You can run the same code multiple times by using a loop.

The first type of loop you will learn is called a while loop because it runs while a specified condition is true and stops once that condition is no longer true.

  • Example:
var myArray = [];

var i = 5;
while(i >= 0) {
  myArray.push(i);
  i--;
}
Enter fullscreen mode Exit fullscreen mode
console.log(myArray); // will display [ 5, 4, 3, 2, 1, 0 ]
Enter fullscreen mode Exit fullscreen mode

In the code example above, the while loop will execute 7 times and
Add the numbers 5 through 0 (inclusive) in descending order to myArray using a while loop.
We also try getting a while loop to work by pushing values to an array.

Iterate with JavaScript For Loops

The most common type of JavaScript loop is called a for loop because it runs for a specific number of times.

  • Example:
var myArray = [];
for (var i = 1; i <= 5; i++) {
  myArray.push(i);
}
Enter fullscreen mode Exit fullscreen mode
console.log(myArray); will display [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

In the following example we initialize with i = 1 and iterate while our condition i <= 5 is true. We'll increment i by 1 in each loop iteration with i++ as our final expression.
we used a for loop to push the values 1 through 5 onto myArray.

Iterate Odd Numbers With a For Loop

For loops don't have to iterate one at a time. By changing our final-expression, we can count by odd numbers.

  • Example:
var myArray = [];
for (var i = 1; i < 10; i += 2) {
  myArray.push(i)
}
Enter fullscreen mode Exit fullscreen mode
console.log(myArray); will display [ 1, 3, 5, 7, 9 ]
Enter fullscreen mode Exit fullscreen mode

Here we push the odd numbers from 1 through 9 to myArray using a for loop.
We start at i = 1 and loop while i < 10. We'll increment i by 2 each loop with i += 2.

Count Backwards With a For Loop

A for loop can also count backwards, so long as we can define the right conditions.

In order to decrement by two each iteration, we'll need to change our initialization, condition, and final expression.

  • Example:
var myArray = [];

for (var i = 9; i > 0; i -= 2) {
  myArray.push(i);
}
Enter fullscreen mode Exit fullscreen mode
console.log(myArray); will display [9, 7, 5, 3, 1]
Enter fullscreen mode Exit fullscreen mode

We start at i = 9 and loop while i > 0. We'll decrement i by 2 each loop with i -= 2. We push the odd numbers from 9 through 1 to myArray using a for loop.

Top comments (0)