I created a class syntax with properties and methods. Properties have arrays and I wanted to create space between those elements on the arrays. When I created a method that return a string with those properties ,I used join(', ') method to make space between the elements of the array.
When I create my instances and called them in the console it doesnt work. It gives this error :
*Uncaught TypeError: this.interests.join is not a function*
here is my code :
class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
* //here is the problem *
let hobbies = this.interests.join(' ,')
return `Hi. I'm ${this.name.first} I am ${this.age} . I like ${hobbies}`;
}
farewell() {
return `${this.name.first} has left the building. Bye for now!`;
}
}
class Student extends Person {
constructor(first, last, age, gender, interests, grade) {
super(first, last, age, gender, interests);
this.grade = grade;
}
}
let ron = new Student('Ron', 'Weasley', 14, 'Quidditch', 3);
let harry = new Student('Harry', 'Potter', 14, ['Quidditch', 'cause problems'], 3);
let hermione = new Student('Hermione', 'Granger', 14, ['Studying', 'Read'], 3);
let neville = new Student('Neville', '', 14, 'Herbiology', 3);
It seems that in some cases (
ronandneville) theinterestsargument you are passing to your constructor isn't an array but a string.Then, when you call the
greetingmethod later, thejoinmethod isn't present on strings hence the error.You should transform the interests given in the constructor in an always-array with something like:
Edit:
As Ivar suggest in the comment below, you are actually sending a number in place of the interests argument.
So, first, reorder your arguments when creating instances, then ensure they are always arrays.