Loops and Interactions
Hello HaWkers, this is the fourth article in our series of articles that will cover the in-depth understanding of our [JavaScript Roadmap - EVERYTHING you need to Learn 🦅](/blog/roadmap-javascript-tudo-o-que-voce-necessa- learn). If you don't know what I'm talking about, click on the previous link.
Well, let's get started!
Repetition loops, or loops, are structures that allow you to repeat a block of code several times, saving lines and facilitating code maintenance. In this article, we will delve into the main types of loops available in JavaScript and how to use them efficiently.
For Loop
The for
loop is one of the most used structures in programming. With it, it is possible to define the initialization, stopping condition, and iteration in a single line. Let's explore its nuances and characteristics, but first why is it important?
// Instead of writing this:text += cars[0] + '<br>';text += cars[1] + '<br>';text += cars[2] + '<br>';text += cars[3] + '<br>';text += cars[4] + '<br>';text += cars[5] + '<br>';
This is the basic syntax of the for
Loop:
for (expression 1; expression 2; expression 3) { // code of the block to be executed}
And knowing this you can write as follows:
// You can write this:for (let i = 0; i < cars.length; i++) { text += cars[i] + '<br>';}
For Loop with Objects
In addition to arrays, we can also use for
loops to iterate through the properties of an object. Using the for...in
loop, we can navigate through all enumerable properties of an object.
const object = { a: 1, b: 2, c: 3 };for (const prop in object) { console.log(`object.${prop} = ${object[prop]}`);}// Output:// object.a = 1// object.b = 2// object.c = 3
For...of Repeat Loop
The for...of
loop makes it easy to iterate through iterable objects, such as arrays and strings, without needing to worry about indexes. Let's see how it works:
const array = [1, 2, 3, 4, 5];for (const value of array) { console.log(value);}// Output:// 1// two// 3// 4// 5
While Repeat Loop
The while
loop creates an iteration that continues as long as the defined condition is true. It is extremely useful in situations where we don't know how many times we will need to iterate.
This is the syntax of the while loop:
while (condition) { routine;}
And this is an example of how to use it:
let n = 0;let x = 0;while (n < 3) { n++; x += n;}console.log(x); // 6
Infinite Loop: A Trap to Avoid
While loops are powerful tools, they can also be dangerous traps. An infinite loop can crash your program, creating an operation that never ends.
// ATTENTION: This is an example of an infinite loop. Do not run this code!while (true) { console.log('This is an infinite loop!');}
Exploring suitable exit conditions and avoiding inadvertently creating infinite loops is vital to writing robust and efficient code.
Do-While Repeat Loop
Similar to while
, the do-while
loop ensures that the block of code is executed at least once regardless of the condition, only checking it at the end of each iteration.
This is the do-white syntax:
of;statement;while (condition);
And this is an example of how to use it:
let result = '';let i = 0;of { i = i + 1; result = result + i;} while (i < 5);console.log(result);// Output: "12345"
Loop with Array
Arrays and loops are inseparable partners in programming. When working with arrays in JavaScript, we have several ways to iterate over them, such as using the map
, filter
, and reduce
methods, which facilitate the manipulation of arrays in a functional and declarative way. But there is also another way, which is probably the most used, which is the famous forEach
:
forEach
forEach
iteration is a high-order function specific to arrays. It allows you to iterate over each element of an array in a simplified way, without the need to manually control the indexes.
This is the syntax of forEach
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
And here is an example of how to use it:
const array = ['a', 'b', 'c'];array.forEach(element => console.log(element));// Expected output: "a"// Expected output: "b"// Expected output: "c"
Using Loops with String Methods
Loops are not just for numbers or arrays; they can also be used with strings! We can, for example, iterate over each character in a string using a for
loop.
const text = 'HaWkers';for (let i = 0; i < text.length; i++) { console.log(text[i]);}// Output:// H// The// W// k// It is// r// s
Using Loops with Asynchronous Functions
Sometimes it may be necessary to use loops with asynchronous functions, and modern JavaScript allows us to do this elegantly with the help of async/await
. Let's look at an example:
const tasks = [1, 2, 3, 4, 5].map(n => async () => { console.log(`Starting task ${n}`); await new Promise(res => setTimeout(res, 1000)); console.log(`Completing task ${n}`);});for (const task of tasks) { await task();}// Output (with a 1 second interval between each set of logs):// Starting task 1// Completing task 1// ...// Starting task 5// Completing task 5
Note: This code must be run in an environment that supports async/await
, and within an asynchronous function.
Keyword continue inside Loops
The continue
keyword allows you to skip the current iteration of a loop, continuing directly to the next iteration. It is a valuable tool to avoid executing unnecessary code in specific situations within a loop.
Let's look at an example where we want to log only odd numbers from an array:
for (let i = 0; i <= 10; i++) { if (i % 2 === 0) { continues; } console.log(i);}// Output:// 1// 3// 5// 7// 9
In this example, we are using continue
to skip code execution for even numbers, logging only odd numbers.
Keyword break inside Loops
The break
keyword, on the other hand, allows you to completely exit a loop, stopping all future iterations. It is used to optimize the code, avoiding unnecessary executions when we have already achieved the desired result.
Let's check it out in action:
for (let i = 0; i <= 10; i++) { if (i === 5) { break; } console.log(i);}// Output:// 0// 1// two// 3// 4
In this example, the loop stops as soon as i
becomes 5, avoiding unnecessary iterations and exiting the loop early.
Nested Loops
Nested loops are loops placed inside other loops. Although powerful, they must be used with caution as they can easily lead to performance issues, especially when working with large data sets.
Let's see how we can use nested loops to create a multiplication matrix:
for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log(`Result of multiplying ${i} and ${j} is: ${i * j}`); }}// Output:// Result of multiplying 1 and 1 is: 1// Result of multiplying 1 and 2 is: 2// ...// Result of multiplying 3 and 3 is: 9
Here, we have two loops: one for i
and one for j
. This allows us to multiply each combination of i
and j
, creating a multiplication table.
Loops and Recursion
Sometimes we can use recursion, a process where a function calls itself, as an alternative to loops. Recursion can offer cleaner, easier-to-understand solutions to complex problems.
function countdown(n) { if (n <= 0) { console.log('Done!'); return; } console.log(n); countdown(n - 1);}countdown(3);// Output:// 3// two// 1// Done!
Loops and DOM Manipulation
Loops can be a powerful tool when combined with DOM manipulation in web development. Below, we will iterate over a list of DOM elements and change their contents:
const itemsList = document.querySelectorAll('li');for (const [index, item] of itemsLista.entries()) { item.textContent = `Item number ${index + 1}`;}
Building Animations with Loops
We can use loops to create dynamic animations on our web pages. Here is an simple example using a for
loop to animate an element's background color change:
const element = document.querySelector('.my-element');for (let i = 0; i <= 100; i++) { setTimeout(() => { element.style.backgroundColor = `rgba(255,0,0,${i / 100})`; }, i * 100);}// In this code, the '.my-element' element will gradually change its background color to red over 10 seconds.
Conclusion
Well HaWkers, as you can see, mastering repetition loops is essential for any JavaScript developer. They offer a powerful and flexible way to iterate over datasets, run repetitive code, and create more complex and efficient algorithms. I hope this guide helps you better understand and use these essential control structures in your daily life as a programmer.
Back to Roadmap JavaScript - EVERYTHING you need to learn 🦅.