Randomly encountered this. When I store array.length in a variable and apply to the for loop condition using operator <= the loop works fine but when I use array.length with the same operator it becomes infinite.
function map(array, callback) {
let k =array.length;
for(let i= 1; i<=k; i++)
{
array[i] = callback(array[i]);
}
return array;
}
console.log(map([1, 2, 3], addTwo));
This works as expected. But when I use this
function map(array, callback) {
for(let i= 1; i<=array.length; i++)
{
array[i] = callback(array[i]);
}
return array;
}
console.log(map([1, 2, 3], addTwo));
Of course i=0; i<array.length;
is the way to do it. But I am curious what's happening inside it.
You can easily see what happens if you add a console.log
in there:
let addTwo = x => x + 2
function map(array, callback) {
for (let i = 1; i <= array.length; i++) {
console.log(i, array.length) // <-- print out i and the length of the array
array[i] = callback(array[i]);
if(i==5) // <-- so we do not run out of memory
return false
}
return array;
}
console.log(map([1, 2, 3], addTwo));
Bottom line is you are saying that the for loop
should keep going as long as i
is less or equal to the array.length
but at the same time once i
reaches the actual length of the array we continue to increase both. i
via i++
and array.length
via array[i] = callback(array[i]);
so there is no end in sight.