-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdestructuring-assignment-or-named-optional-parameters.js
79 lines (66 loc) · 2.14 KB
/
destructuring-assignment-or-named-optional-parameters.js
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
77
78
79
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe",
},
};
/**
* Example with named parameter instead of doing userId(user.id)
* @param {object} id
* @return {number} id
*/
function userId({ id }) {
return id;
}
/**
* Example with named parameters and even a direct "child parameter" value
* @param {object} parameters
* @return {string}
*/
function whois({ displayName, fullName: { firstName: name } }) {
// instead of whois(user.displayName, user.fullName.firstName)
// or return `${user.displayName} is ${user.fullName.firstName}`
return `${displayName} is ${name}`; // (fullName.firstName won't work here)
}
/**
* Example with named parameters but with named key instead of the value
* @param {object} parameters
* @return {string}
*/
function whois2({ displayName, fullName: { firstName } }) {
return `${displayName} is ${firstName}`;
}
console.log(userId(user)); // 42
console.log(whois(user)); // "jdoe is John"
console.log(whois2(user)); // "jdoe is John"
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Setting_a_function_parameters_default_value
/**
* Example with optional parameters
* = {} lets it work even with no input parameters
* @param {object} parameters
*/
function drawChart({
size = "big",
coords = { x: 0, y: 0 },
radius = 25,
} = {}) {
console.log(size, coords, radius);
// do some chart drawing
}
drawChart({
coords: { x: 18, y: 30 },
radius: 30,
}); // big {x: 18, y: 30} 30
drawChart(); // no params works too because function drawChart({...} = {}) {
// more: https://github.com/hchiam/learning-js/blob/master/spread-operator.js
const [message, status] = user
? ["Push Token updated", 200]
: ["User not found", 404];
console.log({ message }); // -> { message: 'Push Token updated' }
// you can also rename destructured elements:
const c = { a: "some value", b: 2 };
const { a: renamedItem } = c;
console.log(renamedItem); // 'some value'