Forward Thinking — a never-complete guide to modern JavaScript #1 For loop
I found that many programmers are not using for loop properly. I think everybody saw code like this:
const arr = [1, 2, 3, 4];
for (let i=0; i < arr.length; i++ ) {
console.log (arr[i]);
}
What is wrong with that? On every loop we are calculating arr length. And this length is not changing, so reading the same information X times is a waste of resources.
Second approach we can see is improved version of previous one:
const arr = [1, 2, 3, 4];
const arrLength = arr.length;/*
* Some superb comment about what is happening
* in this very loop
*/
for (let i=0; i < arrLength; i++ ) {
console.log (arr[i]);
}
Better, but arrLength is out of for loop scope.
So let’s try third one, which I prefer:
const arr = [1, 2, 3, 4];
/*
* Some superb comment about what is happening
* in this very loop
*/
for (let i=0, arrLength = arr.length; i < arrLength; i++){
console.log (arr[i]);
}
All variables which we need in for loop are defined within its scope. It is much shorter and improves memory management (no variable lives longer than it’s necessary).
It is possible because the for loop has the following syntax:
for (initialization; condition; statement ) {
//code block to be executed in each loop
}
We can even make code like that:
const arr = [1, 2, 3, 4];
for (let i=0, arrLength = arr.length; i < arrLength; console.log (arr[i++]) );
But I do not recommend it. It is hard to read and understand.
Last but not least. I know that there are better/different solutions. We can program without for loop at all!
Below is a little example:
const myArray = [1, 2, 3, 4];
const map = f => x => Array.prototype.map.call(x, f)
const log = x => console.log(x);
const logElementsInArray = map(log);
logElementsInArray(myArray);