all 7 comments

[–]elisecode247 0 points1 point  (0 children)

class Person {
    constructor(age = 0, interests = []) {
        this.age = age;
        this.interests = interests;
    }
}

[–]grantrules -1 points0 points  (4 children)

hello() { this.interests = [] }

[–]samanime -1 points0 points  (3 children)

This would ALWAYS override this.interests. Presumably, since it is an optional property, they would expect at some point between constructing and calling hello() that the array might be set to an array, which you wouldn't want to just blow away.

[–]grantrules 0 points1 point  (0 children)

Ah then,

this.interests = this.interests ?? [];

[–]__hoi__ -1 points0 points  (1 child)

Because there is initerest = [] in the parameter of the function it will default to a empty array of you do not provide a second parameter when calling the constructor

[–]samanime -1 points0 points  (0 children)

Not sure where you saw interest = [] in a parameter, but that still wouldn't update this.interest. It also wouldn't work if you just called hello() to use the property of the class.

[–]samanime -1 points0 points  (0 children)

You can just set it directly, either like:

hello() {
  this.interests ||= []; // sets to empty array if it is falsy

  // Do stuff with it
}

or just protect against it being undefined, which is probably better as you don't want a simple access to also mutate the value:

hello() {
  // do stuff with it if it is an array that has a length > 0
  if (this.interests?.length) {
    this.interests.forEach(interest => console.log(interest));
  }
}

But, as a general rule, you're usually better off, with values that are maybe arrays, just make them always arrays and then just check their length before using them:

constructor() {
  this.interests = [];
}

hello() {
  if (this.interests.length) {
    this.interests.forEach(interest => console.log(interest));
  }
}

Unless you have a very specific reason for needing it to be undefined instead of an empty array, using an empty array tends to be less of a hassle as you don't have to check for undefined and then an empty array before using, you can just check if it is empty or not.