I am writing a very easy function where I am checking the even numbers from an array of integer and adding those even numbers into the new array. But after getting the even numbers from first array when I am trying to push into second array its showing undefined.
const arr = [1,2,3,4,5,6];
const newArr = [];
const loop = () => {
for (var item of array) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
};
console.log(loop());
Output
2 4 6 undefined
Why new array is showing undefined.
newArrbut never do anything to it or print itloop()has noreturnstatement, therefore, it implicitly producesundefined. And when you log the return value of executing the functionloop()you see thisundefinedin the console.arris defined: check ...newArris defined: checked ... code iterates overarray... which is nowhere to be seen: check