Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning all objects within an array

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading