How to use join() method in a class constructor?

306 views Asked by At

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);
2

There are 2 answers

1
0xc14m1z On BEST ANSWER

It seems that in some cases (ron and neville) the interests argument you are passing to your constructor isn't an array but a string.

Then, when you call the greeting method later, the join method isn't present on strings hence the error.

You should transform the interests given in the constructor in an always-array with something like:

this.interests = Array.isArray(interests) ? interests : [ interests ]

Edit:

As Ivar suggest in the comment below, you are actually sending a number in place of the interests argument.

constructor(first, last, age, gender, interests)

//            ^      ^    ^      ^        ^
//            |      ++   +---+  +-----+  +----+
//            |       |       |        |       |

new Student('Ron', 'Weasley', 14, 'Quidditch', 3)

So, first, reorder your arguments when creating instances, then ensure they are always arrays.

0
Mitya On

You've got two problems.

Firstly, your class constructor expects interests as the 5th param.

constructor(first, last, age, gender, interests) {

However when instantiating you're passing it as the 4th param, e.g.

let harry = new Student('Harry', 'Potter', 14, ['Quidditch', 'cause problems'], 3);

Furthermore, your typing is inconsistent. interests (notwithstanding that it's passed to the wrong param) is usually passed as an array but sometimes as a string.

let ron = new Student('Ron', 'Weasley', 14, 'Quidditch', 3);

This will cause an error as strings obviously have no .join() method.