Iterations on JavaScript | How, when, which and especially, why me?

Iterations in JavaScript are complicated, perhaps the most complicated concept, especially if you don't have someone to explain them to you step by step. It took me three different video creators and 4 articles written by different people to get the logic but, once you get the logic they are stupidly easy, the problem is, there aren't many good teachers around, or at least not around the free-to-watch videos and cost-free articles out there, it was only after I learned on a paid course about iterations that I actually got it, and I got it at the first try.

Iterations

image.png

If/else statements are control operations, and now we are going to explore Loops, which are also control operations (among many, many others.)

Loops allow us to automate repetitive tasks, tasks that we have to go over and over them.

There's a basic principle in JavaScript - or any other programming language for that matter - to not repeat yourself. Loops allow us to follow this rule perfectly.

A For loop has a counter, and it has three parts: Initial value of a counter,

for(let vote = 2; vote <= 10; vote++){ //1
    console.log("I just voted 2 Hive posts today")
}


1.Inside the parentheses we put the initial value of the counter. We create a variable there, and we set it to a number, where the repetition will begin. We use a let, because the counter will be later updated by the counter. The second part, after the semicolon, is a logical condition that is evaluated before each iteration of the loop (before each time the loop is executed). vote <= 10 ---- vote needs to stay below or equal to ten. If the condition is true, the next iteration of the loop starts, when the condition is false, the code stops running. The third part, after the second semicolon, we set the increase of the counter. Without it, the counter would never increase after each iteration. Then we write the code we want to be repeated inside the brackets.

The code above is almost ready as we have it, but if we run this code, it will just print ten times "Let's vote 2 Hive posts", with no actual difference between each string. We still need to tweak that code a little bit:

for(let vote = 2; vote <= 10; vote++){
    console.log(`I just voted ${vote} Hive posts today`)       // We just need to use the counter variable that we created (vote) to increase the number in the string we are printing out.
}


Output:
I just voted 2 Hive posts today
I just voted 3 Hive posts today
I just voted 4 Hive posts today
I just voted 5 Hive posts today
I just voted 6 Hive posts today
I just voted 7 Hive posts today
I just voted 8 Hive posts today
I just voted 9 Hive posts today
I just voted 10 Hive posts today

Looping through arrays


I'll limit myself to use the same Array I used when I wrote about arrays on my last post. Let's say we want to loop through this array and print all the elements.

const hiveUsers = ["@lunaticpandora", "@cadawg", "@deathwing", "@galenkp", "@abh12345", "@tarazkp", "@jeffjagoe"];

for(let users = 0; users < hiveUsers.length ;users++){      // 2
    console.log(hiveUsers[users], typeof hiveUsers[users]); // 3
}

  1. We use the .length method because we don't want to hard code the value of 5 in case the number of array elements change, we don't have to modify the code. We begin the counter at zero because remember that arrays are zero based, meaning they begin the index at zero for the first position.
  2. I just included the typeof method to show you you can print anything from the loop iterations and the code still works.

Output:
lunaticpandora
cadawg
deathwing
galenkp
abh12345
tarazkp
jeffjagoe
//Notice there is no array, no brackets, no nothing, just the names printed out as is.

Now, we know how "for loops" work but we didn't do anything with the array, we just read the elements and returned them, we didn't do anything! Let's fix that.

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "abh12345", "tarazkp", "jeffjagoe"];
const types = [];   // 4

for(let users = 0; users < hiveUsers.length ; users++){   
    // On the code below we read the elements of the hiveUsers array
    console.log(hiveUsers[users], typeof hiveUsers[users]);
    // On this code we are filling the types array
    types[users] = typeof hiveUsers[users];
    }   

    console.log(types);

  1. We create a variable with an empty array because after the loop, we will fill the array with the result we get.

I kind of want to use another kind of example to show you how "for loops" work, so let's just create a new array.

const promYear = [2010, 2015, 2021];
const beginYear = [];
const yearsOfHighSchool = 3;

for (let i = 0; i < promYear.length; i++){
    beginYear.push(promYear[i] - yearsOfHighSchool);
}
console.log(beginYear);


Output: [ 2007, 2012, 2018 ]

There are two important statements for the "for loop", continue and break, let's explain them:

We use the "continue" statement when we want to exit the current iteration of the loop and continue to the next one. We use break when we want to completely terminate the loop iterations and stop it on its tracks. Let's make up an array on the go:

const array = ["hello", 1, false, "Hola", "Ciao", undefined]      // 5
for (let i = 0; i < array.length; i++){
    if(typeof array[i] !== "string") continue;

    console.log(array[i])       // 6 
}


Output:
hello
Hola
Ciao

  1. Let's say we only want to include in the array those elements that are strings, we must use the typeof method and the continue statement.
    6.We are not modifying the array, we are just creating a new one without the not-string values, that why we print it like that instead of just printing (array)

To use the break statement in any situation, we must establish a condition for the loop to stop. Let's say we want to terminate the loop once we find a boolean value.

const array = ["hello", 1, false, "Hola", "Ciao", undefined]
for (let i = 0; i < array.length; i++){
    if(typeof array[i] === "boolean") break;
    
console.log(array[i]) 
}


Output:
hello
1

Looping through an array backwards

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "abh12345", "tarazkp", "jeffjagoe"];
    for (let i = hiveUsers.length-1 ; i >= 0; i--){     //7
        console.log(hiveUsers[i]);
    }

7.Instead of using ++ to increase the counter by 1, we use -- to decrease it.

Looping inside a loop

const anomadsoul = ["vote", "post", "comment"];
for (let i = 0; i < anomadsoul.length; i++){            // 8
    console.log(`________Anomadsoul will give a ${anomadsoul[i]}___________`);
for (let done = 1; done <=3; done++){
    console.log(`Anomadsoul has done ${[done]} ${anomadsoul[i]}`)
}}


8.we use "i" but we could use whatever, like "action"

To be honest, this is quite tricky, I did it all by myself mom, but it really costed me to understand the logic but, once you get where everything comes from and why you should write the code like this, it is s phenomenal feeling.

//Output:

________Anomadsoul will give a vote___________
Anomadsoul has done 1 vote
Anomadsoul has done 2 vote
Anomadsoul has done 3 vote
________Anomadsoul will give a post___________
Anomadsoul has done 1 post
Anomadsoul has done 2 post
Anomadsoul has done 3 post
________Anomadsoul will give a comment___________
Anomadsoul has done 1 comment
Anomadsoul has done 2 comment
Anomadsoul has done 3 comment

While Loops


The difference between the for loop and the while loop is pretty simple. Both need the same components (a counter where we will begin the counter, a condition to stop the counter, and to increase the counter somehow), but in the while loop we can only specify a condition:

let done = 1;
while (done <= 3) {
    console.log(`Anomadsoul just gave ${done} votes`);
    done++;
}

For this example we needed a counter, but in reality a while loop doesn't need a counter to run, if you notice, the counter is a variable set outside of the loop.
The condition of the while loop doesn't need to be related to any counter, or to anything actually.

For example, if we want to roll a dice and keep rolling it until we get a 4, we don't know how many times we'll have to roll it, but we know we want to stop when we get a 4

let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 4) {                                // 9
    console.log(`You got a ${dice}!`);
    dice = Math.trunc(Math.random() * 6) + 1;       // 10
    if (dice === 4) console.log(`Congrats, you finally got a ${dice}`);   
}


9.We set this condition so, every time the result from running the code is different than 4, it keeps running, and when it is not different than 4, it stops.
10.This is the counter increment (or decrement, we don't know as it is random). Let's call it the counter change.

But this code has a bug, if the first result of the variable dice is 4, then the loop won't even begin running, and we will get a blank result (no errors, just nothing)

But I guess that's for another lesson, right now let's wrap it up here. I hope you enjoyed learning about loops as much as I enjoyed writing about them.

If you made it this far, you are already a little bit versed in loops, or at least enough to call yourself a beginner at JS, but not a complete noob.

This post was quite short compared to my other JS stuff but, the topic is complicated so I decided to leave it here and continue in another one.

I hope this was instructive for you, if you have any comments please do, I will reply to them all.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversion now