What loop should I use, why are there so many?
In this article, I am going to give you my view of what loop you should use and why I see them as beneficial and I hope this means you can push on with your work and avoid the deeper conversation until a later stage.
For Loop
We are all familiar with this one, the first loop most tutorials teach us, which is surprising as it’s not the simplest to read but we all know it and I’m willing to bet that if you are starting then this will be your go-to loop.
Which is fine it does the job perfectly well.
So for the sake of clarity here is an example:
const arr = [1, 2, 3, 4, 5];
for (let i=0; i < arr.length; i++) {
console.log(arr[i])
}
For loop can iterate in reverse:
for (let i = arr.length – 1; i >= 0; i–) {
console.log(arr[i])
}
That said I’ve never needed to iterate over something in reverse! So let’s look at For Of and For In next:
For Of and For In
These loops are the ones you should use as your everyday go-to loops. The key reasons for this are:
Clean and readable syntax You can use ‘Break’ and ‘Continue’ like you would in the traditional For Loop. It pretty much loops over anything.
What is the difference between ‘of’ and ‘in’?
For Of: It loops over the Values
For In: Loops over the Keys.
const arr = [1,2,3,4,5]
arr.six = 6;
arr.seven = 7;
//This array will now look like [1,2,3,4,5,six:6,seven:7]
// OF: iterates over values
for (const value of arr ) {
console.log(value);
}
// Logs:
// 1
// 2
// 3
// 4
// 5
// IN: iterates over keys
for (const key in arr ) {
console.log(key, arr[key])
}
// Logs:
// ‘0’ 1
// ‘1’ 2
// ‘2’ 3
// ‘3’ 4
// ‘4’ 5
// ‘six’ 6
// ‘seven’ 7
We can also iterate over an array of objects:
const numbers = [{one:1},{two:2},{three:3},{four:4}];
for (const number of numbers ) {
console.log(number);
}
//Logs:
// { one: 1 }
// { two: 2 }
// { three: 3 }
// { four: 4 }
And even iterate over a string :
const str = ‘string’;
for (const letter of str) {
console.log(letter)
}
//Logs:
// ‘s’
// ‘t’
// ‘r’
// ‘i’
// ‘n’
// ‘g’
As mentioned earlier these loops work with ‘break’ and ‘continue’ just like the traditional For Loop, which becomes extremely valuable in keeping your code efficient:
for (const letter of string) {
if(letter === ‘t’) break
console.log(letter) }
// Logs only the first letter ‘s’
Errors:
If you attempt to use for…of with an object that is not iterable, it will throw an error. On the other hand, for…in can still be used to loop over the properties of any object, regardless of whether it is iterable or not.
Performance:
for…in can be slower than for…of due to the extra steps involved in property enumeration. However, the impact on performance is generally negligible unless you are working with a large number of properties.
As we can see, the benefits stand out without highlighting them further. So what about forEach() why am I switching my allegiance to For Of?
array.forEach()
The main drawback with forEach() apart from only being of use on arrays, is you can’t stop it. Unlike above where once a condition is met we can enter a ‘break’ clause and the loop would end, forEach() doesn’t work like that.
In the case where you may handle 10000+ rows of data, what happens when we find the result in the first few 100 rows?
Well, nothing we have to sit and wait for the loop to iterate through every row before it finishes.
It is at this point I begin to understand why this does become a discussion about performance and I begin to understand why people are so vocal on the topic.
“but couldn’t I just return out of the loop?” Let’s see what happens when we try:
const array = [1,2,3 … 567890];
array.forEach((num)=> {
console.log(num)
}
// Logs every number up to 567890
array.forEach((num)=> {
if(num === 1001) return
console.log(num)
}
// Logs every number up to 1000, but don’t be fooled
//It is still going to loop through the remaining entries!
132 Comments
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
farmacie online autorizzate elenco: Farma Prodotti – farmacia online senza ricetta
comprare farmaci online con ricetta
acquistare farmaci senza ricetta http://farmaprodotti.com/# Farmacia online miglior prezzo
farmacia online piГ№ conveniente
farmacia online: Cialis generico farmacia – farmacia online piГ№ conveniente
http://jugabet.xyz/# Los jugadores deben conocer las reglas.
Players can enjoy high-stakes betting options.
Slot machines feature various exciting themes.: phtaya login – phtaya login
https://phtaya.tech/# Promotions are advertised through social media channels.
Most casinos offer convenient transportation options.
Los croupiers son amables y profesionales.: jugabet.xyz – jugabet
Online gaming is also growing in popularity.: taya365.art – taya365 com login
https://phtaya.tech/# Casinos often host special holiday promotions.
п»їCasinos in the Philippines are highly popular.
taya777 taya777 Some casinos have luxurious spa facilities.
Manila is home to many large casinos. https://taya777.icu/# Many casinos host charity events and fundraisers.
https://phtaya.tech/# The Philippines has several world-class integrated resorts.
Poker rooms host exciting tournaments regularly.
La seguridad es prioridad en los casinos.: winchile.pro – winchile
The Philippines offers a rich gaming culture.: taya777.icu – taya777 login
https://taya365.art/# Manila is home to many large casinos.
Players enjoy both fun and excitement in casinos.
phtaya login phtaya Online gaming is also growing in popularity.
https://phtaya.tech/# Slot machines attract players with big jackpots.
Live music events often accompany gaming nights.
Some casinos have luxurious spa facilities. http://jugabet.xyz/# Hay casinos en Santiago y ViГ±a del Mar.
Las experiencias son Гєnicas en cada visita.: jugabet chile – jugabet.xyz
La mГєsica acompaГ±a la experiencia de juego.: jugabet – jugabet.xyz
http://taya365.art/# The ambiance is designed to excite players.
Promotions are advertised through social media channels.
The Philippines offers a rich gaming culture. http://phtaya.tech/# Loyalty programs reward regular customers generously.
Algunos casinos tienen programas de recompensas.: jugabet – jugabet chile
http://taya777.icu/# High rollers receive exclusive treatment and bonuses.
Slot machines feature various exciting themes.
phmacao club phmacao club A variety of gaming options cater to everyone.
http://taya777.icu/# The casino scene is constantly evolving.
Some casinos feature themed gaming areas.
Las promociones atraen nuevos jugadores diariamente.: winchile – winchile.pro
Los casinos reciben turistas de todo el mundo.: jugabet casino – jugabet.xyz
Online gaming is also growing in popularity. http://phtaya.tech/# Casino promotions draw in new players frequently.
taya365 taya365 login Casino promotions draw in new players frequently.
Some casinos have luxurious spa facilities.: taya777 app – taya777 login
http://winchile.pro/# Las apuestas deportivas tambiГ©n son populares.
The casino industry supports local economies significantly.
Slot machines attract players with big jackpots. http://phmacao.life/# Players must be at least 21 years old.
The casino atmosphere is thrilling and energetic.: phtaya.tech – phtaya.tech
The casino experience is memorable and unique.: taya365 – taya365
https://phmacao.life/# Casinos often host special holiday promotions.
Some casinos have luxurious spa facilities.
Many casinos provide shuttle services for guests.: taya777 login – taya777 login
A variety of gaming options cater to everyone.: phmacao com login – phmacao com login
https://jugabet.xyz/# Los croupiers son amables y profesionales.
Slot machines attract players with big jackpots.
Las estrategias son clave en los juegos.: winchile – winchile.pro
Resorts provide both gaming and relaxation options.: taya777 register login – taya777 app
phmacao casino phmacao com login The Philippines offers a rich gaming culture.
https://phtaya.tech/# The ambiance is designed to excite players.
Casino promotions draw in new players frequently.
Slot tournaments create friendly competitions among players.: phmacao com – phmacao club
Players can enjoy high-stakes betting options.: phmacao casino – phmacao club
http://jugabet.xyz/# Los jackpots progresivos atraen a los jugadores.
Many casinos have beautiful ocean views.
Visitors come from around the world to play.: phmacao casino – phmacao casino
https://phmacao.life/# A variety of gaming options cater to everyone.
Promotions are advertised through social media channels.
La variedad de juegos es impresionante.: jugabet – jugabet casino
jugabet chile jugabet.xyz Las estrategias son clave en los juegos.
Loyalty programs reward regular customers generously.: taya777 – taya777 login
The gaming floors are always bustling with excitement. http://jugabet.xyz/# Las reservas en lГnea son fГЎciles y rГЎpidas.
http://phmacao.life/# A variety of gaming options cater to everyone.
Poker rooms host exciting tournaments regularly.
Las aplicaciones mГіviles permiten jugar en cualquier lugar.: jugabet.xyz – jugabet
phtaya casino phtaya login Cashless gaming options are becoming popular.
The gaming floors are always bustling with excitement.: taya777 app – taya777 register login
https://phtaya.tech/# Slot tournaments create friendly competitions among players.
Casinos offer delicious dining options on-site.
Promotions are advertised through social media channels.: phmacao.life – phmacao club
http://phmacao.life/# Players must be at least 21 years old.
The ambiance is designed to excite players.
The Philippines offers a rich gaming culture.: taya365 login – taya365
win chile winchile casino Las apuestas deportivas tambiГ©n son populares.
The casino scene is constantly evolving. http://phmacao.life/# Players often share tips and strategies.
Gambling regulations are strictly enforced in casinos.: taya777 register login – taya777.icu
https://phmacao.life/# Casinos often host special holiday promotions.
A variety of gaming options cater to everyone.
Many casinos host charity events and fundraisers.: taya777 register login – taya777 app
Poker rooms host exciting tournaments regularly.: taya365 – taya365 login
http://winchile.pro/# La historia del juego en Chile es rica.
Players can enjoy high-stakes betting options.
Gaming regulations are overseen by PAGCOR.: phmacao casino – phmacao com login
https://phtaya.tech/# Slot tournaments create friendly competitions among players.
Security measures ensure a safe environment.
Players enjoy both fun and excitement in casinos.: phtaya casino – phtaya casino
http://taya365.art/# Many casinos provide shuttle services for guests.
Many casinos have beautiful ocean views.
La Г©tica del juego es esencial.: winchile.pro – winchile
best no prescription pharmacy http://familypharmacy.company/# online pharmacy delivery usa
family pharmacy online pharmacy delivery usa online pharmacy delivery usa
top online pharmacy india: Mega India Pharm – MegaIndiaPharm
mexico drug stores pharmacies: mexican pharmaceuticals online – xxl mexican pharm
mail order pharmacy no prescription https://discountdrugmart.pro/# drugmart
MegaIndiaPharm: MegaIndiaPharm – Mega India Pharm
discount drug pharmacy: discount drug mart – online canadian pharmacy coupon
Online pharmacy USA: online pharmacy delivery usa – family pharmacy
legit canadian online pharmacy: pharmacy canadian superstore – easy canadian pharm
prescription free canadian pharmacy https://megaindiapharm.com/# Online medicine home delivery
cheapest pharmacy to fill prescriptions with insurance https://discountdrugmart.pro/# discount drug pharmacy
Cheapest online pharmacy: Cheapest online pharmacy – Best online pharmacy
Best online pharmacy Online pharmacy USA cheapest pharmacy to fill prescriptions without insurance
canadian pharmacy no prescription needed https://megaindiapharm.com/# MegaIndiaPharm
Best online pharmacy: family pharmacy – Best online pharmacy
canadian pharmacy without prescription https://easycanadianpharm.com/# best canadian pharmacy
canadian pharmacy no prescription needed https://xxlmexicanpharm.com/# mexican pharmaceuticals online
Online pharmacy USA: Online pharmacy USA – Online pharmacy USA
canadian pharmacy no prescription needed https://easycanadianpharm.shop/# easy canadian pharm
cheap pharmacy no prescription drugmart discount drug mart pharmacy
international pharmacy no prescription: reputable online pharmacy no prescription – Online pharmacy USA
easy canadian pharm: canadian pharmacy tampa – canadian pharmacy meds reviews
non prescription medicine pharmacy https://easycanadianpharm.shop/# reliable canadian pharmacy
promo code for canadian pharmacy meds http://familypharmacy.company/# family pharmacy
Best online pharmacy: family pharmacy – online pharmacy delivery usa
drug mart drug mart discount drug mart pharmacy
easy canadian pharm: easy canadian pharm – easy canadian pharm
uk pharmacy no prescription http://megaindiapharm.com/# top 10 pharmacies in india
safe canadian pharmacies: online canadian pharmacy reviews – canada rx pharmacy world
canadian pharmacies not requiring prescription http://familypharmacy.company/# Best online pharmacy
best no prescription pharmacy https://megaindiapharm.com/# MegaIndiaPharm
pharmacy website india: Mega India Pharm – п»їlegitimate online pharmacies india
online pharmacy discount code http://xxlmexicanpharm.com/# pharmacies in mexico that ship to usa
reputable indian online pharmacy: Mega India Pharm – mail order pharmacy india
online pharmacy no prescription http://easycanadianpharm.com/# best canadian online pharmacy
discount drug mart pharmacy: drugmart – drugmart
drugmart discount drugs discount drug pharmacy
cheapest pharmacy for prescription drugs https://easycanadianpharm.shop/# pharmacy canadian superstore
MegaIndiaPharm: india pharmacy mail order – MegaIndiaPharm
Mega India Pharm: Mega India Pharm – pharmacy website india
easy canadian pharm: easy canadian pharm – easy canadian pharm
easy canadian pharm canadian neighbor pharmacy easy canadian pharm
online pharmacy no prescription http://megaindiapharm.com/# Mega India Pharm
drug mart: drug mart – discount drugs
cheapest pharmacy for prescriptions without insurance https://xxlmexicanpharm.com/# medication from mexico pharmacy
canada online pharmacy no prescription https://xxlmexicanpharm.shop/# mexican border pharmacies shipping to usa
mail order pharmacy no prescription https://megaindiapharm.shop/# top online pharmacy india
easy canadian pharm: medication canadian pharmacy – easy canadian pharm
cheapest pharmacy to fill prescriptions with insurance https://easycanadianpharm.shop/# cross border pharmacy canada
discount drugs: discount drug pharmacy – non prescription medicine pharmacy
prescription drugs canada buy online: legitimate canadian mail order pharmacy – canadian pharmacy 1 internet online drugstore
pharmacy coupons https://megaindiapharm.shop/# best india pharmacy
promo code for canadian pharmacy meds http://megaindiapharm.com/# india pharmacy
discount drug pharmacy: discount drug mart – drugmart
canadian prescription pharmacy https://megaindiapharm.com/# Mega India Pharm
buying prescription drugs from canada https://megaindiapharm.shop/# indianpharmacy com
discount drug mart pharmacy: non prescription medicine pharmacy – us pharmacy no prescription
canadian pharmacy no prescription needed https://discountdrugmart.pro/# discount drugs