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.