JS Loops (for of) Tutorial 🚀

beginner
20 min

JS Loops (for of) Tutorial 🚀

Welcome back to CodeYourCraft! Today, we're diving into the world of JavaScript loops, specifically the for...of loop. By the end of this tutorial, you'll have a solid understanding of this versatile loop type, and you'll even get to practice with two real-world examples. 🎯

What is a Loop? 📝

In programming, a loop is a control structure that allows us to repeat a specific block of code as many times as necessary. This is incredibly useful when dealing with arrays, lists, or any other iterable objects.

Introducing the for...of Loop 💡

The for...of loop is a modern and flexible way to iterate over iterable objects such as arrays, strings, and even custom iterable objects. It's cleaner and easier to understand than its predecessor, the for loop.

How the for...of Loop Works 📝

  1. The for...of loop initializes a variable (often called value) with the current value of the iterable object.
  2. It then enters the loop and executes the code block.
  3. The loop then advances to the next value in the iterable object, and the process repeats until all values have been iterated.

Syntax 📝

javascript
for (const value of iterableObject) { // Your code here }

In the above example, iterableObject is the object we're iterating over, and value is the current value in the iterable object. The const keyword ensures that we create a new variable for each iteration, which is particularly useful when dealing with arrays or other complex objects.

Practical Example: Iterating Over an Array 🎯

Let's say we have an array of numbers and we want to calculate their sum:

javascript
const numbers = [1, 2, 3, 4, 5]; let sum = 0; for (const number of numbers) { sum += number; } console.log(sum); // Output: 15

In this example, we're initializing a variable sum to keep track of the total, and then we're using a for...of loop to iterate over the numbers array. For each iteration, we add the current number to our sum.

Practical Example: Iterating Over a String 🎯

Now let's say we have a string and we want to count the number of vowels it contains:

javascript
const word = "HelloWorld"; let vowelCount = 0; for (const char of word) { if (char === "a" || char === "e" || char === "i" || char === "o" || char === "u") { vowelCount++; } } console.log(vowelCount); // Output: 5

In this example, we're iterating over each character in the word string. For each iteration, we check if the character is a vowel. If it is, we increment our vowelCount.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `for...of` loop in JavaScript?

Quick Quiz
Question 1 of 1

What is the syntax for a `for...of` loop in JavaScript?

That's it for today! In our next lesson, we'll delve deeper into the for...of loop, exploring more advanced examples and best practices. Until then, happy coding! 💡