I created a project to check an array to update a car collection and came across an issue that I cannot explain. I'm relatively new to JS and still getting my bearings.
My code works fine, as in it gives me the results I want to see only if I call the function once. It is supposed to take a car that is not part of my carsOwned array, dump it into carsWanted and then display the carsWanted array.
If I call my function once, it will do all of this correctly. However if I call the function a second time with another vehicle that is not part of the carsOwned array. It's as if I never called my function the first time, it seems the array is being cleared after each time it is executed.
function updateCarCollection(cars) {
let carsOwned = ["Lamborghini Aventador", "Ferrari 488", "Bentley Continental", "Audi RS7"]
let carsWanted = []
if (carsOwned.indexOf(cars) === -1) {
carsWanted.push(cars);
console.log("I don't have this car yet, but I added it to the cars I want.");
} else if (carsOwned.indexOf(cars) > -1) {
console.log("This car is already part of my collection");
}
console.log(carsWanted);
}
updateCarCollection("Ferrari 428");
//even though I called it the first time it will behave ad if I never called the function the first time
updateCarCollection("Spyder 718");