JavaScript Tricks
JS
S
JavaScriptSome tricks to use along the way
1// Swap variable values (via array destructuring)
2let a = 'x1', b = 'x2';
3[a,b] = [b,a];
4
5// Parallel Asynchronous Flow (via array destructuring)
6const [user, somethingAsync] = await Promise.all([
7 fetch('/user'),
8 doSomethingAsync()
9]);
10console.warn(user);
11
12// Pretty print on console (for debugging purposes)
13const a = 1, b = 2;
14console.log({a,b});
15
16// One line function definition
17var findMax = (arr) => Math.max(...arr);
18findMax([1,2,3,4]);
19
20var sumAll = (arr) => arr.reduce((a,b) => (a+b),0);
21sumAll([1,2,3,4]);
22
23// Concat arrays
24const first = [1,2,3,4]; const second = [5,6,7,8];
25const concatAll = [...first, ...second];
26console.log(concatAll)
27
28// Shallow Copy (prototype values are shared *__proto__)
29var obj1 = {a: 1};
30const objCopy = {...obj1};
31console.log(objCopy);
32
33const arr = [1,2,3,4];
34const arrCopy = [...arr];
35console.log(arrCopy);
36
37// Named Parameters
38const callTelemetry = ({telemetry, count}) => {
39 console.log(`doStuff.. ${telemetry} ${count}`);
40}
41callTelemetry({telemetry: 'anthena1', count: 44, randomStuff: 55});Created on 12/3/2017