-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdestructuring.js
More file actions
76 lines (57 loc) · 1.8 KB
/
destructuring.js
File metadata and controls
76 lines (57 loc) · 1.8 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Destructuring in JavaScript
// What is "destructuring"?
// It allows you to pull out values from an array or object and immediately assign that value to a variable.
// This prevents you from needing to declare a bunch of variables.
// Example
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const obj = {
name: 'Ruslan',
age: 26,
job: 'React Developer'
}
const [one, two] = arr // Destructuring array values into variables
const { name } = obj // Destructuring object properties into variables
const { age } = obj
console.log(one)
console.log(two)
console.log(name)
console.log(age)
// Skip values with a comma
const [, , three, four, , , , eight] = arr
console.log({ three, four, eight })
// Default Values
const [first = 1, second = 2] = arr // Assign default values if values are undefined
const { language = 'English' } = obj
console.log({ first, second, language })
// ...rest property
const [nine, ten, ...rest] = arr // Use the rest operator (...) to capture remaining values
const { job, ...restTwo } = obj
console.log(rest)
console.log(restTwo)
// Nested Destructuring
const arr2 = [[1, 2], [3, 4]]
const obj2 = {
innerObj: {
myName: 'Ruslan'
},
innerObj2: {
myAge: 26
}
}
const [[One, Two], [Three, Four]] = arr2 // Destructuring nested arrays
console.log({ One, Two, Three, Four })
const { innerObj: { myName }, innerObj2: { myAge } } = obj2 // Destructuring nested objects
console.log({ myName, myAge })
const objName = { Name: 'Ruslan' }
const { Name: MyName } = objName // Renaming destructured variable
console.log({ MyName })
// Function param destructuring
const person = {
name: 'Roman',
age: 33
}
function greet({ name, age }) { // Destructuring function parameters
return `Hi, ${name}. You're ${age}.`
}
const greeting = greet(person)
console.log(greeting)