Meal Maker: How does the setter function set the values for the _courses?

Link to the Meal Maker Project:
https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-objects/projects/meal-maker

const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: []
  },

  get appetizers () {
     return this._courses.appetizers;
  },

  set appetizers (data) {
     this.courses.data = appetizers;
  },

  get mains () {
     return this._courses.mains;
  },

  set mains (data) {
     this.courses.data = mains;
  },

  get desserts () {
     return this._courses.mains;
  },

  set desserts (data) {
     this.courses.data = desserts;

  }
};

appetizers, mains, and desserts are arrays and you can’t simply assign values to them. You’ll have to think of another way - is there an array function that can do this? Remember your training!

1 Like

I can use the .push method to assign values to the arrays. What is the meaning of the setters in this instance?

Object properties can be any data type, even functions or other objects. From my understanding, the setter methods allow you to handle each type appropriately and in line with your goal. You can ask yourself: what does it mean to set this property value? Do you want an array to be copied to the new value? Add elements to an array? If it’s a number or string maybe you simply want to reassign the value. And the answer to that question would be the meaning of your setter.

If the property is an array and your goal is to write a setter that adds elements to that array, you can write the setter to do just that - using the .push() method as you mentioned.

Study this example for a hint, and maybe a little more insight…

u = {
  _a: ['a'],
  get a () {
    return this._a
  },
  set a (x) {
    this._a.push(...x)
  }
}
u.a = [1, 2, 3, 4, 5]
console.log(u)
u.a = 'b'
console.log(u)

Output

{ _a: [ 'a', 1, 2, 3, 4, 5 ], a: [Getter/Setter] }
{ _a: [ 'a', 1, 2, 3, 4, 5, 'b' ], a: [Getter/Setter] }

Notice how JS has let us create the a property to correspond with the declared underscore property (the backing variable)? And it is telling us the value of that property is a Getter/Setter.

We can only pass one value to a setter, but it can be any type so long as we, as @ryansup pointed out, validate it or can be confident it is a usable type. Above we are able to pass an array or a single value because using the spread operator we break up the sequence before it is pushed to the array.

The important thing to note is the assignments. They are both normal object syntax. The magic is done at the setter.

2 Likes

Thank You! :grinning:

Thank You! :star_struck:

2 Likes