How does property access works and what does the following line do?

Viewed 59

I've found following code at JS tutorial page and I'm quite unsure what does it do and how it work. Can you please explain what is it for and what it does?


// Source is : https://javascript.info/property-accessors

let user = {
  name: "John",
  surname: "Smith",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" "); <<<<<<<<<<<<<<<<<<<<<<<<<
  }
};

// set fullName is executed with the given value.

user.fullName = "Alice Cooper";

alert(user.name); // Alice
alert(user.surname); // Cooper
2 Answers
user.fullName = "Alice Cooper";

Calls the set fullName of user:

set fullName(value) {
    [this.name, this.surname] = value.split(" "); <<<<<<<<<<<<<<<<<<<<<<<<<
}

Which then does a .split to the given string "Alice Cooper", dividing it into an array by the space in the string. So the result of "Alice Cooper".split(" ") is an array ["Alice", "Cooper"].

This array is then immediately destructured into the user object's name and surname properties.

Related