1//destructuring array
2const alphabet = ['a', 'b', 'c', 'b', 'e'];
3const [a, b] = alphabet;
4console.log(a, b);
5//Expected output: a b
1const book = {
2 title: 'Ego is the Enemy',
3 author: 'Ryan Holiday',
4 publisher: {
5 name: 'Penguin',
6 type: 'private'
7 }
8};
9
10const {title: bookName = 'Ego', author, name: {publisher: { name }} = book, type: {publisher: { type }} = book } = book;
1let [a, b] = [9, 5]
2[b, a] = [a, b]
3console.log(a, b);
4//Expected output: 5,9
1Object Destructuring =>
2//
3 The destructuring assignment syntax is a JavaScript expression that makes it
4possible to unpack values from arrays,
5or properties from objects, into distinct variables.
6//
7example:
8const user = {
9 id: 42,
10 is_verified: true
11};
12
13const {id, is_verified} = user;
14
15console.log(id); // 42
16console.log(is_verified); // true
17
1let [greeting = "hi",name = "Sarah"] = ["hello"];
2
3console.log(greeting);//"Hello"
4console.log(name);//"Sarah"
5
1const hero = {
2 name: 'Batman',
3 realName: 'Bruce Wayne',
4 address: {
5 city: 'Gotham'
6 }
7};
8
9// Object destructuring:
10const { realName, address: { city } } = hero;
11city; // => 'Gotham'