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!
3 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 article helped me a lot, is there any more related content? Thanks!
Vink van Wijngaarden T, Birkenhäger JC, Kleinekoort WM, van den Bemd GJ, Pols HA, van Leeuwen JP where can i buy priligy online safely