Use [] to find tag! Example: [flutter, javascript]

Javascript made easy
Javascript made easy

Chapter 5

For of

remove_red_eye 964 Times
spellcheck 277 Words, 1769 Characters
*Note: this book is still ongoing until it has a finished label.

1. Explanation of for of

In the realm of JavaScript, for of stands as an unassuming hero that allows us to explore the beauty of each element within an iterable without dealing with indices or relying on the traditional methods of for in. The for of syntax is a luxurious loop that spoils developers with remarkable code readability, providing ease in traversing values in an array, string, or other iterable objects.

2. Example of for of

Let's witness for of in action with an example. Suppose we have an array containing the vibrant colors of the rainbow that we want to explore:


const rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];

for (const color of rainbowColors) {
  console.log(`Color of the day: ${color}`);
}

In this code snippet, for of allows us to traverse each color in the rainbowColors array without bothering with indices or requiring additional method calls. The code becomes vivid and concise.

3. Case Study

Let's apply for of to a real-world case—parsing words in a string:


const favoriteQuote = 'Coding is an art of turning caffeine into code';

const words = favoriteQuote.split(' ');

for (const word of words) {
  console.log(`Found a word: ${word}`);
}

In this case study, we use for of to iterate through each word in the favoriteQuote string by splitting it using the split method. The result? Each word is displayed without complexity, highlighting the beauty of for of in presenting code readability.

With for of, we not only iterate through elements of an iterable, but we also follow a pleasant rhythm in JavaScript code writing. Whether traversing a rainbow of colors or parsing words in a sentence, for of adds a magical touch to every adventure in the world of JavaScript programming.

Next Article (While)
Content Navigation