Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 295
behdad99 Avatar asked Sep 18 '25 22:09

behdad99


2 Answers

value.split creates a list with two elements (in this special case "Alice Cooper" => ["Alice", "Cooper"]) and the elements are unpacked into [this.name, this.surname]

this.name contains the first element of the array and this.surname contains the second element.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

like image 84
Thomas Sablik Avatar answered Sep 21 '25 12:09

Thomas Sablik


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.

like image 34
Swiffy Avatar answered Sep 21 '25 12:09

Swiffy