-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path10 Practical JavaScript Tricks
More file actions
96 lines (55 loc) · 1.53 KB
/
10 Practical JavaScript Tricks
File metadata and controls
96 lines (55 loc) · 1.53 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* 1. Transform the arguments object into an array.*/
var argArray = Array.prototype.slice.call(arguments);
2. Sum all the values from an array.
var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17
3. Short circuit conditionals.
if (hungry) {
goToFridge();
}
hungry && goToFridge()
4. Use logical OR for conditions.
function doSomething(arg1){
arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}
5. Comma operator.
let x = 1;
x = (x++, x);
console.log(x);
// expected output: 2
x = (2, 3);
console.log(x);
// expected output: 3
6. Using length to resize an array.
var array = [11, 12, 13, 14, 15];
console.log(array.length); // 5
array.length = 3;
console.log(array.length); // 3
console.log(array); // [11,12,13]
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
7. Swap values with array destructuring.
let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // -> 2
console.log(b) // -> 1
8. Shuffle elements from array.
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]
9. Property names can be dynamic.
const dynamic = 'color';
var item = {
brand: 'Ford',
[dynamic]: 'Blue'
}
console.log(item);
// { brand: "Ford", color: "Blue" }
10. Filtering for unique values.
const my_array = [1, 2, 2, 3, 3, 4, 5, 5]
const unique_array = [...new Set(my_array)];
console.log(unique_array); // [1, 2, 3, 4, 5]