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.
You can do it simply with forEach.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
either return the newArray or execute the loop method and print the new Array.
The reason why you get undefined is because loop is currently a void operator and returning nothing. so if you want the loop method to return the array then the second code sample I showed is the better solution. if you just want to print the array then the first one does the trick.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
or
const arr = [1,2,3,4,5,6];
const loop = () => {
const newArr = [];
for (var item of arr) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
return newArr
};
console.log(loop());
both will work.