Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    3 Quizzes
Lesson 7, Topic 3
In Progress

JavaScript: Reverse Looping

Yasin Cakal 18 Nov 2021
Lesson Progress
0% Complete

What if we want to log 3, 2, 1, and then 0 in the for loop? We can make our loop run backward by making simple changes to the expressions!

To run a backward for loop, we must do the following:

  • In the initialization expression, set the iterator variable to the highest desired value.
  • When the iterator variable is less than the desired amount, set the stopping condition.
  • After each iteration, the iterator should decrease in intervals.
for (let counter = 5; counter >= 0; counter--){
  console.log(counter);
}

The output of the following block of code will be:

5
4
3
2
1
0

When writing/changing loops, it’s possible that our stopping condition isn’t met, resulting in the dreaded infinite loop, which effectively prevents our programming from doing anything else! 

Responses

Leave a Reply

%d bloggers like this: