Setters meant to prevent wrong data types from being entered are not working

This Codecademy exercise has me creating setters to prevent object properties from being set with incorrect data types. As far as I can tell, my code matches exactly what Codecademy’s “get unstuck” video shows and yet I am still able to set my object properties to whatever data types I want. When I print, it should return ‘Meal or price was not set correctly’ but instead it prints “today’s special is 10 for burger dollars!” There are no errors messages, what am I missing?

const menu = {
_meal: ’ ',
_price: 0,
set meal(mealToCheck) {
if (typeof mealToCheck === ‘string’) {
return this._meal = mealToCheck;
}
},
set price(priceToCheck) {
if (typeof priceToCheck === ‘number’) {
return this._price = priceToCheck;
}
},
get todaysSpecial() {
if (this._meal && this._price ) {
return today's special is ${this._meal} for ${this._price} dollars!
} else {
return ‘Meal or price was not set correctly!’
}
}
};

menu._meal = 10;
menu._price = ‘Burger’;

console.log(menu.todaysSpecial)

At the end of your file, right before console.log - change the lines to menu.meal and menu.price

Your code is manually setting the _meal and _price properties instead of using the .meal and .price setters :slight_smile:

2 Likes

In addition to the above response, consider that setters need getters. Read up on this in the technique writing. Also, setters don’t return anything, they only set their respective properties.

a = {
    _prop: 'prop',
    get prop () {
        return this._prop
    },
    set prop (value) {
        this._prop = value
    }
}

Furthermore,

get todaysSpecial

should not be written as a getter, just a method. It should employ the getters when polling the variables.

todaysSpecial () {
    if (this.meal && this.price) {

    }
}
1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.