Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Introducing ES2015 Classes Getter and Setter Methods

Ben Ahlander
Ben Ahlander
7,528 Points

Why is my set name(input) returning `firstName lastName undefined`?

'use strict';

class Student {

  get name(){
    return `${this.firstName} ${this.lastName}`;
  }

  set name(input){
  let name = input.split();
  this.firstName = name[0];
  this.lastName = name[1]
}

  constructor({ firstName, lastName, age, interestLevel = 5 } = {}) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.interestLevel = interestLevel;
  }
}

let stevenJ = new Student({firstName: 'Steven', lastName: 'Jones', age: 22})

console.log(stevenJ.name);

stevenJ.name = "Steven Jennings"

console.log(stevenJ.name);

1 Answer

Steven Parker
Steven Parker
231,236 Points

According to the documentation for split(), if the argument is omitted "the array returned contains one element consisting of the entire string". So name[0] (firstName) gets the whole name and name[1] (lastName) is "undefined".

To fix it just supply an argument to split:

  let name = input.split(' ');