I am getting an undefined error after logging each element of the set. please have a look at the code snippet bellow
let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];
const fruits = new Set(arrayFruits);
const itrate = fruits.forEach(fruit =>{
console.log(fruit);
});
console.log(itrate);
forEach do not have any return value. Undefined is printed as part of iteration even if you remove console.log(fruit) from iteration you will still see undefined printed in console.
Please do mention what your use case is when asking the question.
According to the documentation, forEach returns undefined.
console.log is also undefined as it does not explicitly return anything.
You can essentially write your function like this to understand it better.
let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];
const fruits = new Set(arrayFruits);
fruits.forEach(fruit =>{
console.log(fruit);
});
This will print all the values in your set. If you copy-paste this snippet into a browser's console such as Chrome, it will log the result of the function as well. In this case, forEach returns undefined so undefined will be printed at the end.
what you probably need
let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];
const fruits = new Set(arrayFruits);
let itrate = []
fruits.forEach(fruit =>{
itrate.push(fruit)
});
console.log(itrate);