I'm new to JavaScript and working on a personal program which creates car objects and stores them in an array, I am having issues with returning all array elements as only the first array element is returned.
const carFactory = {
_cars:[
{
make: 'default',
model: 'default',
year: 0,
}
],
get cars(){
if(this._cars.length > 0 ){
for(let i = 0; i < this._cars.length; i++){
return `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}`;
}
}else{
return `Please add car details`;
}
},
addCar(carMake, carModel, carYear){
this._cars.push({
carMake,
carModel,
carYear
})
}
}
carFactory.addCar('Toyota', 'Corolla', 2003);
console.log(carFactory.cars);
The issue with your code is that the return statement inside the for loop only returns the first car object in the _cars
array and terminates the loop. To return all cars, you can concatenate the car objects into a string and return it after the loop:
const carFactory = {
_cars:[
{
make: 'default',
model: 'default',
year: 0,
}
],
get cars(){
if(this._cars.length > 0 ){
let allCars = '';
for(let i = 0; i < this._cars.length; i++){
allCars += `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}\n`;
}
return allCars;
}else{
return `Please add car details`;
}
},
addCar(carMake, carModel, carYear){
this._cars.push({
make: carMake,
model: carModel,
year: carYear
})
}
}
carFactory.addCar('Toyota', 'Corolla', 2003);
console.log(carFactory.cars);
Output:
Car Make: default - Car Model: default Manufacture Year: 0
Car Make: Toyota - Car Model: Corolla Manufacture Year: 2003