-1

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));
  • 2
    Yes, that's because the function returns and stops executing after you access the first value. – Take-Some-Bytes May 18 '22 at 23:35
  • Right, `return` stops further execution of your function. You should figure out what you are trying to do. If you want to log every item in the array, move your `console.log` to within the `for` loop instead of calling it just once on the result of the function call. – Alan H. May 18 '22 at 23:36
  • 1
    Does this answer your question? [Does return stop a loop?](https://stackoverflow.com/questions/11714503/does-return-stop-a-loop) – pilchard May 18 '22 at 23:43

2 Answers2

2

Using return will end the loop in the first iteration

try

const numArr = [2,4,6,8,10];

const iterate = (array) => {
    for (let i = 0; i < array.length; i++) {
        console.log(array[i])
    }
};

iterate(numArr);
pilchard
  • 12,414
  • 5
  • 11
  • 23
Grambam
  • 424
  • 1
  • 3
  • 17
0

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);
Bergur
  • 3,962
  • 12
  • 20