Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ricardo Moreira
Ricardo Moreira

Posted on • Edited on

     

Loops in JavaScript with examples

Loops are something that is with us always since the beginning of our never ending journey of learning JavaScript(or any programming language) so let's focus on them. The best way for me to learn is create something with what I am learning so I try to have examples for all the loops where you can see what they do and how we use them

What loops we will cover

*while loop
*do...While loop
*for
*for..3.in
*for...of

So first let’s define what is aloop and why we need to use them in JavaScript?
Do you know when you like a music so much that you just listening it over and over? Well that is a loop. For programming a loop is a way to iterate over something like an array or an object for example. With loops we make sure our code is DRY. Theloop will loop till the condition is met or loop if the condition is met and till the condition is false.

A infinite loop is loop that has not ending and most likely it will crash your app/website

While Loop

Thewhile loop it runs as long the condition evaluated is true. Think of it as a conditional, anif statement but instead of running once, run as long the condition is true.
If you don’t write the condition or write a condition that will never turn false, i.e, is always true the loop never ends.

Syntax:

while(condition){//code to be executed as long the condition is true}

Let's print all number between 0 to 5:

leti=0;while(i<6){console.log(i);i++;}

So what is happening here? First you set the variable to 0 outside theloop. Then you write the while condition that isi < 6, so as longi is less than 6 the code above is going to run.
What is the code? Everything that is inside the brackets, so in this case, the printing the variable( the number) and the add one to that variable.

So it starts in 0. Zero less than 6? Yes, so printi that is 0 and add 1. After how much isi? Yes it’s 1, still lower than 6 so do it again tilli is 6. Because 6 is not smaller than 6 theloop ends and what is printed is:

leti=0;while(i<6){console.log(i);i++;}/*  0  1  2  3  4  5   */

Let's get real

For me the best way to learn is seeing the practicability of the situation/problem, in this case the loop. I will try to be the most practical I can but fell free to tell me if I am not being to clear or how can I improve.

This is is just a small example, I would say it's nothing that will never be need at least like this:)

It’s new Year eve and you want to create a small 10 seconds countdown and till 0 or till it's New year say how many seconds to New Year Eve and when reach 0 it will say “Happy new Year”.

So what happen here?

I will not getting in details about the DOM Manipulation but basically we set aid in ourhtml then we in our js
const message = document.querySelector("#container") and there is where we will display our messagemessage.innerHTML=`${countdown}. Also I’m usingtemplate literals.

Now thewhile loop . We set the variableseconds to 10 that is where we want to be start it, then we set the variablecountdown to an empty string where we will print in JS the countdown.

Then ourwhile statement says that as long the seconds variable is bigger than 0 we write the message and set the variable seconds todecrease one second.
After we just set when it reaches zero. So is outside the loop
countdown =${countdown} ${seconds} Happy new Year.

So theconst message will display the countdown variable during the countdown and show accordingly the message.

do...while Loop

Thedo…while works a bit different. The big difference is that thedo… while loop runs at least once. Basically it says to do something while this condition is true running always at least once.

Syntax:

do//statement or code to executewhile(condition)

Now let's see a situation where it only run once:

leti=0;do{i++;console.log(`I run at least${i} times`);}while(i<0);console.log(`I run a total of${i} times`);// expected result: "I run at least 1 time"// "I run a total of 1 times"

We set the variable to0 and set the loop to add one to each time it iterates and to do it (set the condition to) as long I is less than zero. I put a console.log inside the statement and other outside to see what it prints.

So first thei is 0, and we add one and print “I run at least 1 time”. Then we check the condition: is i less than 0 ? Welli now is 1 and is bigger than 0 so the loop stop and it will print “I run a total of 1 times.
If you want to see the difference change the condition to 5 for example

leti=0;do{i++;console.log(`I run at least${i} times`);}while(i<5);console.log(`I run a total of${i} times`);/* expected result:"I run at least 1 time""I run at least 2 time""I run at least 3 time""I run at least 4 time""I run at least 5 time""I run a total of  5 times"*/

Here you can see how it works when it loops more than once.Thei starts with 0 then we add 1, it becomes 1 . it prints “I run at least one time”. Then because I is still less than 5 adds one more and do the same till I is 5 and then prints all is above.

for loop

One of the most used loops in JavaScript is thefor loop. When I start coding with JS, this was one of the ones I used more till today. In the beginning I was not getting so much how it work so I try to explain in a way that I would understand when I started
In the for loop, the code is repeated until the condition evaluates to false.One of the uses of the for loop is to loop over an array.

Syntax:

for([initialization];[condition];[final-expression])

So when in use, would be looking something like this:

for(leti=0;i<5;i++){//do something}

To explain first let’s go to a simple example. You want to loop all numbers from 0 to 4 and print them, the loop above will be the one to use.

So the initialization (i=0) is where we define a variable, because we want to start at 0 we define the variable as 0.

The condition(i<5) is the expression that in the end of each loop is going to to evaluated and when it becomes false the loop stops. So in this case, in each loop it’s checked if i isless than 5.

The final expression(i++) normally is used as an increment . What you have to take in account is that the final expression occurs before the condition is evaluated

The// do something part is the code that it will run as long the condition(i<5) is true.
In the for loop you can use the break or continue statement.

So let’s see a more real example. You have a website where you want to add movies that you saw and display them on screen.
First in our html let’s create our div where we will represent our movies.

<h1>Movies I see</h1><divid="movies"></div>

In our js we create the array with the movies that we can add more or delete .

letmovies=["Constant Gardener","Batman","Pulp Fiction","Heat","Godfather"];

Now let’s get our div from our html with agetElementById:

letmyMovies=document.getElementById("movies");

Then we create an empty string where we going to render all the movies.

letmyList="";

Now we want to loop over the movies that we have and we can create that with the for loop.

for(leti=0;i<5;i++){console.log(movies[i]);}

So what happens in the loop ? First we create a variable and set to0. Why 0? To start in our first element. If we change it to 1, you will see that it will not print the movie “Constant Gardner”. After we set the condition that is, to print whilei is less than 5. Why 5 ? because is the number of movies we have. Then we addi++ to add always one to each loop. Then we just need to add what we want in each loop and in this case we just want to console.log it – We writemovies[i] to write each movie separated. If you would write only

console.log(movies);

It would print the array of movies 5 times, and not the 5 movies.

And what can we do to improve it? Well what if you want to add another movie? You had to change the condition toi<6 and 7 if you had another and so on. And that isn't really productive. So let’s make it dynamic.

We want that it loops till the variable that we are using to loop (i) is less that the number of movies right? And in programming the number of elements in an array ( number of movies in this example) is thelength of the array so we can write the code like this:

for(leti=0;i<movies.length;i++){console.log(movies[i]);}

And just like that we don’t need to worry if we add another movie, because it will loop always.
Now let’s also render in the screen. We can do it by creating a bullet point in each time it loops.

for(leti=0;i<movies.length;i++){console.log(movies[i]);myList=myList+`<li>${movies[i]}</li>`;}

What we did here? So themyList was an empty string right? So in each loop we want that inside our empty string will be an element of the array while we loop in that string.

To make the code better let’s wrap everything around a function

functionmyMovies(){letmyMovies=document.getElementById("movies");letmyList="";for(leti=0;i<movies.length;i++){console.log(movies[i]);myList=myList+`<li>${movies[i]}</li>`;}myMovies.innerHTML=`${myList}`;}myMovies();

Now we just create the HTML element with the function we created and render the data that is on themyList.

for in

So accordingly toMDN, thefor...in iterates over enumerable properties of an object as for example theobject.keys. For example, constructor or prototype properties are not consideres enumerable so you don’t see them when running afor…in

So even that in Js, everthing is anobject , you shouldn’t usefor…in inarrays. The main reason for that isfor…in iterates in arbitrary order and when iterating over an array, the index is important. So we focus on why and how to use them in an object

Syntax:

for(letkeyinobject){//code in the loop}

So thekey name here is the name variable to assign the object. Is thei in the for loop. And as like in thei in the for loop, you can give it any name. Theobject is the actual object, so you will put the object name you going to loop.
So let’s see how it works and what it does in this example. You have an object that is a person object.

letperson={name:"Steve",age:35,city:"London"}

Now using ourfor...in let’s loop and see what we get:

for(letkeyinperson){console.log(key);}//name//age//city

And we get the properties of the object person, the keys of the object. Do get the values you can do:

for(letkeyinperson){console.log(key);console.log(person[key]);}//name//Steve//age//35//city//London

To make it more clear let’s do

for(letkeyinperson){console.log(`${key} -${person[key]}`);}//name - Steve//age - 35//city - London

So that works just fine and it’s useful, but what happens when we have an object constructor?

Note: If you are seeing loops for the first time, object constructor might seem more advanced and I will talk about it in a future post. For this example, assume that you want to create many persons objects. So you have to add one by one. But if you can create an object constructor with the properties that all persons will have would be easy right? Then we have the object constructor
So let’s create that object constructor.

letPerson=function(name,yearofBirth,job){this.name=name;this.yearofBirth=yearofBirth;this.job=job;};

Then we add a function to that object:

Person.prototype.calculateAge=function(){console.log(2019-this.yearofBirth);};

Now let’s create some objects:

letRicardo=newPerson("Ricardo",1992,"teacher");letMarika=newPerson("Marika",1987,"designer");ricardo.calculateAge();marika.calculateAge();

Now let’s loop over the Marika object:

for(varkeyinmarika){console.log(marika[key]);}/*Marika1987designerƒ () {  console.log(2019 - this.yearofBirth);}*/

Besides the properties of the objectMarika it also loop over the function and that is because thefor…in iterates over all properties of the prototype chain. So we can loop over the properties that has the key object with thehasOwnProperty method:

for(varkeyinmarika){if(Person.hasOwnProperty(key)){console.log(marika[key]);}}/*Marika1987designer*/

So you can use thefor…in to loop over the properties names and to check from an object witch are the ones with some property like the key property for example

for...of

The last loop we will talk about is thefor…of. It works on iterable objects like arrays and strings for example. It was presented with ES6 as an alternative toforEach
.
The syntax is similar to thefor…in just changing the in/on. AndyYou should usefor…in only in plan Objects andfor…of don’t work in Objects.

Syntax:

for(letkeyofobject){//code in the loop}
letingredients=["dough","tomato","cheese"];for(letkeyofingredients){console.log(key);}//dough//tomato//cheese

You can see right away that can do the same as the for loop but with more clean and less code
Also works for strings:

constname="Ricardo";for(constkeyofname){console.log(key);}/*RICARDO*/

Also works formap,objects andsets but we will not focus on them on this post.
One thing that it doesn’t work is on plain Objects and that is because objects are not “iterable”.

But a good use offor…of is on a Node List. For example if you have some titles in one page with the same class and you wanton click to change the color of them. Enter thefor…of

So the html has a bunch of titles with the same class.
In our JS file we get them with :

constelements=document.querySelectorAll(".names");

and then we just add thefor…of:

for(constelementofelements){element.addEventListener("click",()=>{element.classList.add("active");});}

Theactive class is the class that we want to add when clicking that will make the text change color and position.
And that’s that.

There is plenty to talk about loops still but with this hopefully you can start using them in your projects and know which one you want to use. Let’s get coding.

Happy to hear your feedback about this post and how can it be improved.
You can follow me onInstagram where I post every week, snippets, projects I am working and other code related stuff. All other links you find on myprofile.

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
armn profile image
armn
  • Joined

Great read, thanks! You have a small typo though:

for(letkeyonobject){//code in the loop}

should be "let keyof object" :)

CollapseExpand
 
mugas profile image
Ricardo Moreira
Creating BizBox 🖥️🍃 Coding ⌨️ Food 🥘Entrepreneurship 📚 https://twitter.com/mugas11
  • Location
    Helsinki
  • Work
    Freelance developer at Good Stuff Creations
  • Joined

Thank you for the heads up :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Creating BizBox 🖥️🍃 Coding ⌨️ Food 🥘Entrepreneurship 📚 https://twitter.com/mugas11
  • Location
    Helsinki
  • Work
    Freelance developer at Good Stuff Creations
  • Joined

More fromRicardo Moreira

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp