Lesson 2
JavaScript Loops: For, While, and Enhanced Loops
Topic Overview

Greetings, Explorer! In this lesson, we will delve into the essential tools of JavaScript loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring each cup is brewed quickly and consistently. In this lesson, we will explore the universe of looping in JavaScript and gain hands-on experience by applying loops to JavaScript arrays and strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

JavaScript
1let friends = ["Alice", "Bob", "Charlie", "Daniel"]; 2 3for (let i = 0; i < friends.length; i++) { 4 // `i` is the index that changes with each iteration 5 // For each friend, print the greeting 6 console.log("Hello, " + friends[i] + "! Nice to meet you."); 7} 8 9// Output: 10// Hello, Alice! Nice to meet you. 11// Hello, Bob! Nice to meet you. 12// Hello, Charlie! Nice to meet you. 13// Hello, Daniel! Nice to meet you.

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in JavaScript

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop is typically for (initialization; condition; iteration) { loop body }, where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed, which generally updates the value of the loop control variable. Here is how it generally works:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.
  2. Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends, and the flow jumps to the next statement after the loop block.
  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.
  4. Loop Body: The block of code to be executed in each loop.

Let's print a range of numbers using a for loop:

JavaScript
1for (let num = 0; num < 5; num++) { 2 console.log(num); 3} 4 5// Output: 6// 0 7// 1 8// 2 9// 3 10// 4

In each cycle of the loop, the variable num is updated after executing the code inside the block.

Enhanced For Loop in JavaScript

The for loop is versatile and can work with any sequence-like structure in JavaScript, such as strings and arrays. In JavaScript, the enhanced for loop, known as the for...of loop, is used to traverse these collections more simply and safely since it eliminates the need to manually control the loop variable.

JavaScript
1let fruits = ["apple", "banana", "cherry"]; 2 3// `fruit` stands for each fruit in the `fruits` array 4for (let fruit of fruits) { 5 console.log(fruit); 6} 7 8// Output: 9// apple 10// banana 11// cherry

In the above example, the fruit variable stands for each element in the fruits array. The loop body executes once for each item in the fruits array, with fruit being a reference to the current element in each iteration.

Similarly, we may loop through strings (which can be considered containers of characters):

JavaScript
1let word = "hello"; 2// `ch` is each individual character in `word` 3for (let ch of word) { 4 console.log(ch); 5} 6 7// Output: 8// h 9// e 10// l 11// l 12// o

In the example above, ch stands for each character in the word string. The loop repeats for each character in the string word. For each repetition, it will print the specific character, hence printing hello one character at a time.

While Loop in JavaScript

While loops in JavaScript continuously execute their content until a particular condition becomes false. Here's a simple example:

JavaScript
1let num = 0; 2// The loop keeps running until `num` is no longer less than 5 3while (num < 5) { 4 console.log(num); 5 // Increase `num` by 1 at the end of each iteration 6 num++; 7} 8 9// Output: 10// 0 11// 1 12// 2 13// 3 14// 4

As you can see, before each iteration, JavaScript checks the condition (num < 5). If it's true, the loop continues; otherwise, the loop breaks.

Applications of Looping

Loops are integral to programming. They are extensively used in various sections of a program, such as summing elements in an array and parsing through text.

JavaScript
1let numbers = [1, 2, 3, 4, 5]; 2 3let total = 0; 4// `num` is each number in `numbers` 5for (let num of numbers) { 6 total += num; // Add each number in the array 7} 8console.log(total); // print the total sum 9 10// Output: 11// 15
JavaScript
1let text = "hello"; 2let vowelCount = 0; 3// `ch` is each character in `text` 4for (let ch of text) { 5 // If a vowel letter is found, increment the count 6 if (ch === 'a' || ch === 'e' || ch === 'i' || ch === 'o' || ch === 'u') { 7 vowelCount++; 8 } 9} 10console.log(vowelCount); // print the count of vowels 11 12// Output: 13// 2
Lesson Summary and Practice

Congratulations on mastering JavaScript loops! We've brushed up on for and while loops and have seen how to loop over containers like arrays and strings. Now, it's time for some beneficial practice exercises to solidify your learning. The more problems you solve, the better you'll become. Let's proceed further on our journey into the depths of programming!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.