forked from Swap76/Learn-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdestructuring.js
More file actions
32 lines (19 loc) · 1.14 KB
/
destructuring.js
File metadata and controls
32 lines (19 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// As data coming from the server is very big then there is better way of getting the data out of object
const a = { // Suppose this is the object coming from server then
name: "Swapnil",
age: 19,
college: "SIES"
};
// By using Destructuring we can get the data of specific keys out into variables
const { name, age, college } = a; // This way name variable gets "Swapnil" this is possible because the object also has same key
console.log(name); // Output Swapnil
const { name: Myname } = a; // This way Myname variable get assigned the value of name key in from object a
console.log(Myname); // Output Swapnil
array = [1, 2, 3, 4]; // Array Declaration
const [first, second, , fourth] = array; // Array Destructuring
// In this the Order of variables matters the most as arrays don't have keys
// For skipping some values we can do that using as shown here we have skipped the third value
console.log(fourth); // Output 4
newArray = ["Swapnil", 19, "Shinde"]; // New array
const [firstName, , lastName] = newArray; // Destructured the firstName and lastName
console.log(`My name is ${firstName} ${lastName}`);// Output My name is Swapnil Shinde