1

I wanted to display a simple array's items on the console, using foreach. It dispalys all the items(it's OK), but it displays "cars : undefined" at the end. I dont want to display "cars : undefined", but only the 3 items of the array. How to do ?

var cars = [{
    year: 2011,
    type: "Volvo"
}, {
    year: 1999,
    type: "Volvo"
}, {
    year: 2003,
    type: "Volvo"
}];
console.log("1");

console.log("cars : " + cars.forEach(a => console.log(a)));
console.log("2");

3
  • 1
    forEach() returns undefined. You're logging that value. Commented May 30, 2022 at 9:56
  • 1
    The forEach never returns anything, so undefined is correct Commented May 30, 2022 at 9:58
  • 1
    you could use a map, if you want to return something Commented May 30, 2022 at 9:59

2 Answers 2

3

forEach() returns undefined. try like this

var cars = [{
    year: 2011,
    type: "Volvo"
}, {
    year: 1999,
    type: "Volvo"
}, {
    year: 2003,
    type: "Volvo"
}];
console.log("1");

console.log("cars : ");
cars.forEach(a => console.log(a))
console.log("2");
Sign up to request clarification or add additional context in comments.

Comments

2

console.log outputs a string, but returns undefined. So, the inner one writes your data, returns undefined, and the outer one writes 'cars: undefined'

=> You should produce a string inside the log function, like this :

console.log("cars :" + cars.map(a => ` ${a.type} ${a.year}` ));

That will log:

cars : Volvo 2011, Volvo 1999, Volvo 2003

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.