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(; = "Steven Jennings"


1 Answer

Steven Parker
Steven Parker
179,718 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(' ');