Search code examples
javascriptsetter

Uncaught SyntaxError: Setter must have exactly one formal parameter


I'm trying to understand getters and setters on JS and I can't seem to get pass this error. Can anyone provide any insight as to why I'm getting this error?

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(y, e){
        this.year = y;
        this.edition = e;
    }
};

Uncaught SyntaxError: Setter must have exactly one formal parameter


Solution

  • The setter function is called when you assign the value that setter represent:

    var obj = {
      set a(newVal) { console.log("hello"); }
    }
    obj.a = 1; // will console log "hello"
    

    As you can see it doesn't make sense for a setter to take multiply arguments, but it gives you the freedom to manipulate the value before it is set:

    var person = {
      surname: "John",
      lastname: "Doe",
      get fullname() {
        return this.surname + " " + this.lastname;
      },
      set fullname(fullname) {
        fullname = fullname.split(' ');
        this.surname = fullname[0];
        this.lastname = fullname[1];
      }
    };
    
    console.log(person.fullname); // "John Doe"
    person.fullname = "Jane Roe";
    console.log(person.surname); // "Jane"
    console.log(person.lastname); // "Roe"