This loop only returns the first index of the array and stops there.
const numArr = [2,4,6,8,10];
const iterate = (array) => {
for (let i = 0; i < array.length; i++) {
return array[i]
}
};
console.log(iterate(numArr));
This loop only returns the first index of the array and stops there.
const numArr = [2,4,6,8,10];
const iterate = (array) => {
for (let i = 0; i < array.length; i++) {
return array[i]
}
};
console.log(iterate(numArr));
As Take-Some-Bytes mentioned in his comment it is because of the return statement. In JavaScript functions will stop executing when a return statement is called.
In your case, you call the function, the function starts looping through the array, it starts at the first item, sees a return statement and stops execution of the function.
On another note: This iterate method seems a little boiler plate or re-inventing things that are already available.
For example, have you tried:
const numArr = [2,4,6,8,10];
numArr.forEach(item => {
console.log(item)
})
The code above does the same thing as:
const numArr = [2,4,6,8,10];
const iterate = (array) => {
for (let i = 0; i < array.length; i++) {
console.log(array[i])
}
};
iterate(numArr);