As the title says atm i am looping through and array and when I try to return it, it only returns the first index.
const array = ['blue', 'orange', 'brown', 'pink'];
const stuff = () => {
let store = [];
let arr = array;
console.log('this returns ['blue', 'orange', 'brown', 'pink']', array);
for(let i = 0; i <= arr.length; i++) {
console.log('Log individual indexes', arr[i]);
const element = arr[i];
console.log('stores those indexes in element', element);
// in console I see:
// blue
// orange
store.push(element);
return element; // function only returns blue
}
}
I know its because a return stops the loop but how can I return all the values in the array:
3
Answers
You just need to move the return out of the for loop, here is the fixed code.
The issue is indeed that the
return
statement inside the loop stops the function after the first iteration, which is why you’re only getting the first element (‘blue‘) returned. To return all the values in the array, you need to move thereturn
statement outside of the loop.As you mention the issue is in return, you need to take it out of the loop but still, it will show you an error due to syntax issue in
Update this line by
full code is: