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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With