Home > Enterprise >  JS : console.log displays "undefined" in the end of an array of objects
JS : console.log displays "undefined" in the end of an array of objects

Time:05-31

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");

CodePudding user response:

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");

CodePudding user response:

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
  • Related