8. Loops

The syntax of JavaScript loops was devised using the famous languages of the time, such as C++ or Java. They had to be made sexy by trying to make them look as much as possible like what already existed. With the new version of the standard, called ES6, history has repeated itself. New loops have been developed to modernize and improve JavaScript, using other famous reference languages such as Python, among others.

Value iteration loop: For-of

In a simple and pleasant way we will iterate over an array, or list, to get its content.

for (variable of array/object) { ... }

An example.

let listaFrameworks = ['Angular', 'React', 'Vue', 'Ember', 'Elm'];

for (const framework of listaFrameworks) {
    console.log(framework);
}
//Angular
//React
//Vue
//Ember
//Elm

Key iteration loop: For-in

The difference lies in the word in instead of of, the rest of the structure is the same.

for (variable in array/object) { ... }

Its purpose is to give us the position occupied by each element. An example.

let listaFrameworks = ['Angular', 'React', 'Vue', 'Ember', 'Elm'];

for (const posicion in listaFrameworks) {
    console.log(posicion);
}
//0
//1
//2
//3
//4

Key and value iteration loop: forEach

It's very interesting since it lets you have the best of for-in and for-of. It returns the position and value of each element in our array. Although it's true that its structure differs from what was mentioned above.

array.forEach(function callback(valor, posicion, arrayUsado) { ... });

An example getting the values and positions.

let listaFrameworks = ['Angular', 'React', 'Vue', 'Ember', 'Elm'];
listaFrameworks.forEach((valor, posicion, array) => {
    console.log(posicion + '-' + valor);
});
//0-Angular
//1-React
//2-Vue
//3-Ember
//4-Elm

The array argument is nothing more than a copy of the one we are iterating over.

let listaFrameworks = ['Angular', 'React', 'Vue', 'Ember', 'Elm'];
listaFrameworks.forEach((valor, posicion, array) => {
    console.log(array);
});
//['Angular', 'React', 'Vue', 'Ember', 'Elm']
//['Angular', 'React', 'Vue', 'Ember', 'Elm']
//['Angular', 'React', 'Vue', 'Ember', 'Elm']
//['Angular', 'React', 'Vue', 'Ember', 'Elm']
//['Angular', 'React', 'Vue', 'Ember', 'Elm']

Traditional loop with For

Without depending on an array, we can iterate over a range of numbers of our choosing.

for ([initialExpression]; [condition]; [incrementExpression])
  statement

In this example, where we show the numbers from 0 to 3.

// Traditional for loop
for (let i = 0; i <= 3; i += 1) {
    console.log(i);
}
//0
//1
//2
//3

A simpler way to do the same thing is by iterating over Arrays, as we learned in the Arrays lesson. A very versatile function is generating ranges with Array.from.

const rango = Array.from({length: 4}, (v, i) => i);

for (const num of rango) {
    console.log(num)
}
//0
//1
//2
//3

We will go deeper into this later.

The possibilities of for are wide-ranging if you're skilled at playing with the increment and its condition.

// Decrease from 10 to 0
for (let i = 10; i > 0; i -= 1) {
    console.log(i);
}
// Interval of 5 from 0 to 100
for (let i = 0; i <= 100; i += 5) {
    console.log(i);
}

Traditional loop with While

This loop is as powerful as it is dangerous. It only accepts one condition, so if our software doesn't change that variable, we'll have an infinite loop.

let play = true;

while (play) {
    console.log('I run until someone changes play to false');
}

A simple example that iterates over the numbers from 30 to 50.

let num = 30;
while (num <= 50) {
    num += 1;
    console.log(num);
}

Ranges

In other languages (Python, Clojure, PHP...) we have a range function specially designed for creating sequences. Unfortunately, we don't have one in JavaScript, but they can still be built in different ways.

If we wanted to iterate over the numbers from 0 to 3, we could use fill() together with map() to generate an array that can be iterated.

const miRango = Array(4).fill().map(function(valor, indice) {
    return indice;
});

console.log(miRango);
// [0, 1, 2, 3]

And to finish.

for (const num of miRango) {
    console.log(num)
}
//0
//1
//2
//3

Or using Array.from() as we've seen.

for (const num of Array.from({length: 4}, (v, i) => i)) {
    console.log(num)
}
//0
//1
//2
//3

On the other hand, if I need to get the positions together with the values, I need to use a native function called entries().

let listaFrameworks = ['Angular', 'React', 'Vue', 'Ember', 'Elm'];
for (const [pos, valor] of listaFrameworks.entries()) {
    console.log(pos + ' esta ' + valor);
}
//0 esta Angular
//1 esta React
//2 esta Vue
//3 esta Ember
//4 esta Elm

I have a function that is comparable to using range() in Python or any other similar language. A complete, optimal, and flexible solution for creating sequences.

Final notes

You can solve almost any need using forEach or for-of. However, other types of loops exist because they remain practical. Exploring and applying them appropriately is up to you as a frontend developer.

Activity 1

In an input, indicate how many elephants you want in your song. For example, if you indicate you want 3, 3 paragraphs will be generated with the following structure.

<p>1 elephant was swinging On a spider's web As it saw it wasn't falling It went to fetch another elephant</p>
<p>2 elephants were swinging On a spider's web As they saw it wasn't falling They went to fetch another elephant</p>
<p>3 elephants were swinging On a spider's web As they saw it wasn't falling They went to fetch another elephant</p>
Activity 2

Create the following select elements with their respective option elements using loops.

  • The month numbers: from 1 to 12.
  • The days of a month, for example from 1 to 31.

Nightmare level 👹

  • The years from 1900 to today, using the current year.
  • The months in Spanish.
Activity 3

Create an array with 5 places you've traveled to. Then, print them using HTML with:

  • for/of
  • forEach
  • for
Activity 4

Generate a Christmas tree using the 🟢 emoji in HTML. Use text-align: center to help.

       ⭐
       🟢
     🟢🟢🟢
    🟢🟢🟢🟢🟢
  🟢🟢🟢🟢🟢🟢🟢
🟢🟢🟢🟢🟢🟢🟢🟢🟢
     🟫🟫🟫
     🟫🟫🟫

With a select, swap out the height. In the example it's 5.

Nightmare level 👹

Add randomly colored balls as if they were decorations.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.