const buchstaben = [ ...'hallo welt' ]; 
//=> ["h", "a", "l", "l", "o", " ", "w", "e", "l", "t"]

Anwendungen

Kopieren

//Beispiel 1
const array1 = [1,2,3]; 
const array2 = array1;

const array3 = [ ...array1 ]; 

console.log(array1 === array2); //true
console.log(array1 === array3); //false


//Beispiel 2
const obj1 = {name: "Max", land: "Schweiz"}; 
const obj2 = obj1; 

const obj3 = {...obj1 }; 

console.log(obj1 === obj2); //true
console.log(obj1 === obj3); //false

obj2.land ="BRD"
console.log(obj1.land); //BRD

obj3.land ="Österreich"
console.log(obj1.land); //BRD

Keine Deep Copy

Unverschachtelte Objekte und Arrays werden noch kopiert:

const obj1 = { name: "Max", land: { name: "BRD", region: "Bayern" } };
const obj2 = { ...obj1 };

obj2.land = { name: "BRD", region: "Sachsen" };
console.log(obj2.land === obj1.land); //false

Sobald die Objekte oder Arrays verschachtelt sind, werden diese nicht kopiert (nur die Referenz darauf):

const obj3 = {
  name: "Max",
  land: { name: "BRD", region: { ebene1: "Bayern", ebene2: "Franken" } }
};

const obj4 = { ...obj3 };
console.log(obj4.land === obj3.land); //true

obj4.land.region.ebene2 = "Oberbayern";
console.log(obj4.land.region.ebene2, obj3.land.region.ebene2); //"Oberbayern" "Oberbayern"

Kompositionen

const obj1 = { stadt: "Berlin", bundesland: "Berlin" };
const obj2 = { land: "BRD", metropole: true };
const neuesObj = { ...obj1, ...obj2, kontinent: "Europa" };

console.log(neuesObj);
// {bundesland: "Berlin",kontinent: "Europa",land: "BRD",metropole: true,stadt: "Berlin"}

Destrukturierung

const standort = ["München", "Bayern", "BRD"];
const [stadt, , bundesland] = standort;
console.log(stadt, bundesland); // "München" "BRD"
const standort = { stadt: "München", bundesland: "Bayern", land: "BRD" };
const { stadt, land } = standort;
console.log(stadt, land); //"München" "BRD"

Rest Operator

const nummern = [1, 2, 3];
const [ersteNummer, ...restDerNummern] = nummern;
console.log(ersteNummer, restDerNummern); // 1 [ 2, 3 ]