Mark As Completed Discussion

In this lesson, we will learn about loops and iterations in programming, with a focus on the following key points,

  1. What are iterations in programming?
  2. Working with loops and related concepts in JavaScript.

For the Python version of this lesson, please click here.

During programming, you may encounter situations when you want to repeat a block of code a certain number of times. Repeating the same code, again and again, is slow, untidy, and is prone to errors. These kinds of problems in programming are dealt with concepts called loops and iterations. This automates the process of applying a similar operation to a collection of elements, or statements within a program.

One example where loops are extremely helpful is repeated calculations for different values. Imagine you need to calculate the final scores of each student in a class of 30 students. Performing the same calculations for each student requires time and is an exhausting process. In situations like this, loops are extremely helpful. We can specify the calculations within the code block of the loop, and the program can automatically calculate the scores of each student. Using loops, the burdensome process of calculations is reduced to only a few lines of code!

Iteration and Iterables

Let's understand the concept of iteration and iterables first. These terms pop up commonly when working with this concept! Iteration refers to a concept in programming where a set of statements, or a code block is executed repeatedly. Programming languages provide several language features to make it easier for us to implement this feature. Loops are a programming structure that implements this concept. They repeat a set of specified instructions unless told otherwise.

Another important concept is iterables. An iterable is an object that is iterated upon, that is, you can go to each of its elements one by one, and access them. Sequences such as arrays and strings are examples of iterables in JavaScript.

Iteration and Iterables

These concepts will become clearer once we move on to the examples.

Loops

Loops are a programming structure that perform the task of iteration. That is, they iterate over a collection of objects. Each programming language has different types of loops. However, there are two kinds of loops that are more common and present in most programming languages; for loops and while loops.

Let's see the implementations of both of them in JavaScript.

For Loops

For loops are used to iterate over a sequence of elements. They are used when a code block needs to be repeatedly executed a known number of times.

In JavaScript, for loops are set by specifying three statements after the for keyword in parenthesis.

  1. The first statement sets a variable before the loop starts. This statement is executed only once before the execution of loop.
  2. The second statement defines a condition for the loop, which is continuously checked during the execution.
  3. The third statement is responsible for changing the value (such as incrementing or decrementing) of the variable every time the code block for the loop is executed.

The variable initialized in the first statement is important as that same variable is used in second and third statements to specify the condition and value change. It can also be used within the loop block to access the elements. Let's understand this with an example.

Suppose you want to print a list of numbers from 0 to 9.

JAVASCRIPT
1//prints a sequence of numbers from 0 to 9
2for (var i = 0; i < 10; i++){
3    console.log(i);
4}

The usefulness of loops come into play when we use them on sequences such as strings or arrays. By accessing the length of sequences using the .length property, we can access each element in the given sequence.

In the below example, the loop is executed 5 times, and each time an element from the array is accessed using indexing to print all elements in the array.

JAVASCRIPT
1//prints all values in the vegetables list using indices
2var vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for (var i = 0; i < vegetables.length; i++){
4    console.log(vegetables[i])
5}

While Loops

While loops are another type of loops that are used to iterate over a sequence of elements under a certain condition. If the condition is true, the loop keeps executing, but once the condition becomes false, the loop stops executing.

The execution of while loops can be understood by the following illustration.

While Loops

Consider a similar example of printing the first 10 integers. Unlike for loops, in while loops a variable needs to be initialized before the loop. This is because the while loop condition requires the value of the said variable. In the example below, we initialize i before the loop, and keep incrementing it until all the first 10 integers are printed.

JAVASCRIPT
1var i = 0;
2while (i < 10){
3    console.log(i);
4    i++;
5}

Note: ++ is the post-increment operator. It is used when a variable needs to be incremented by 1. This is a common notation that you will see in while loops!

Let's look at another example where we specify a different condition. This loop keeps executing until it encounters an odd element from the list numbers.

JAVASCRIPT
1// loop stops once odd number is encountered from the list
2var i = 0;
3var numbers = [0, 2, 4, 5, 7];
4while ((numbers[i] % 2) == 0){
5    console.log(numbers[i]);
6    i++;
7}
8console.log("Odd number found!");

Are you sure you're getting this? Fill in the missing part by typing it in.

How many times will the following loop be executed?

JAVASCRIPT
1var fruits = ["apple", "mango", "strawberry", "grapes", "orange", "watermelon", "peach"]
2fruits.pop()
3
4for (var i = 0; i < fruits.length; i++){
5    console.log(i)
6}

Write the missing line below.

Let's test your knowledge. Is this statement true or false?

The following code block on execution will generate an error.

JAVASCRIPT
1var numbers = [0, 2, 4, 5, 7]
2for (var i = 0;  i < numbers; i++){
3    console.log(numbers[i])
4}

Press true if you believe the statement is correct, or false otherwise.

Important Tips when working with Loops

There are certain important keywords that one must be aware of while working with loops.

  • break statement is an important keyword when working with loops. It can force stop a loop during the execution, before the terminating condition is set to false (in a while loop), or before it completes all its number of iterations (in a for loop).
  • continue statement allows to stop the current iteration and continue with the next. All the code below the continue statement will not be executed and the loop skips to the next iteration.
  • Infinite loop is a condition that occurs if the loop keeps executing forever. This is a common error that may arise when you begin to work with loops. The common cause of the error is usually an error in the loop condition or initialization. The only way to stop an infinite loop is to force stop the execution. This is why it's important to check your loop conditions and initializations, and be careful with them else your program will never stop executing!

Let's test your knowledge. Is this statement true or false?

The letter 'p' will not be printed in the execution of following code block.

SNIPPET
1var text = "Loops"
2var i = 0
3while (i < text.length){
4  if (text[i] == "o"){
5      i += 1
6      continue
7  }
8  console.log(text[i])
9  i += 1
10}

Press true if you believe the statement is correct, or false otherwise.

Are you sure you're getting this? Click the correct answer from the options.

What is the result of the execution of following code block?

SNIPPET
1var a = 5
2while (a <= 5){
3    if (a < 5){
4        break
5    }
6    console.log(a)
7}

Click the option that best answers the question.

  • The program will loop indefinitely
  • The value of a will be printed once
  • The value of a will be printed 5 times
  • The loop will not be executed

Summary

Iterations are an important concept in programming. Like functions, iterations help us reduce the number of lines of code that need to be written, and helps in code reusability and modularity. Moreover, loops allow us to specify the number of times the code needs to be reused (or repeated), or the specific condition under the code block needs to be reused.

One Pager Cheat Sheet

  • By leveraging loops and iterations, we can automate the process of applying a similar operation to a collection of elements in a program.
  • Iteration and loops are programming structures that repeatedly execute a set of instructions, while iterables are objects, such as arrays and strings, that can be accessed one element at a time.
  • Loops are used to iterate over a collection of objects, with for and while loops being the most common types found in most programming languages, such as JavaScript.
  • In JavaScript, For loops are used to iterate over a sequence of elements by specifying three statements: a variable initiated before the loop starts, a boolean condition to be checked each time, and a value change to take place every time the code block is executed.
  • While loops are used to iterate over a sequence of elements, while a condition remains true, and they require initialization before the loop.
  • The loop will run while i is lesser than fruits.length, which is currently 6, because the last element was removed using fruits.pop().
  • The for loop syntax requires the comparison to compare the iterator variable with the array length, a number value, but the code uses the array numbers which will result in an error.
  • One must be aware of the break, continue, and infinite loop keywords when working with loops to ensure the program does not execute indefinitely.
  • The code will print all letters except for "o", skipping over it with continue and still printing p.
  • This program is an example of an infinite loop, since there is no code to change the value of a, and the loop condition of a <= 5 will always remain true.
  • Iterations (or loops) help us reduce lines of code, improve code reusability, and enable us to specify the number of times a code block needs to be repeated.