Javascript Shorthand
1. Play with .bind()
1 | // document.querySelector |
2. Clone object, array
a. Object1
2// shallow clone an object
const newObj = Object.assign({}, obj);
or1
2// deep clone an object
const newObj = JSON.parse(JSON.stringify(obj));
b. Array1
2
3
4const a = [1, 2, 3];
const b = a.slice();
console.log(b); // -> [1, 2, 3]
console.log(b === a); // -> false
3. Swap value
1 | const x = 1, y = 2; |
4. Random with range
1 | const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; |
5. trim()
DIY
1 | function trim(x) { |
6. Cast arguments
to Array
1 | const args = Array.prototype.slice.call(arguments); |
7. Max, min in array
1 | const numbers = [1, 8 , 10 , -125 , 28 , 100 , 215, -85]; |
8. Reset Array
1 | const a = [1, 2, 3]; |
9. Delete Array emlement
a. Wrong way1
2
3
4
5const arr = ["a", 1, -5, "cde"];
console.log(arr); // -> ["a", 1, -5, "cde"]
delete arr[2];
console.log(arr); // -> ["a", 1, undefined, "cde"]
console.log(arr.length); // -> 4
b. Right way1
2
3
4
5let arr = ["a", 1, -5, "cde"];
console.log(arr); // -> ["a", 1, -5, "cde"]
arr.splice(2, 1);
console.log(arr); // -> ["a", 1, "cde"]
console.log(arr.length); // -> 3
10. Use &&
or ||
instead of if
and if else
a. if
1
2
3let a = 10;
if (a === 10) console.log("a === 10"); // -> a === 10
if (a !== 5) console.log("a !== 5"); // -> a !== 5
->1
2
3let a = 10;
a === 10 && console.log("a === 10"); // -> a === 10
a === 5 || console.log("a !== 5"); // -> a !== 5
b. if else
1
2
3let a = 10;
if (a === 5) console.log("a === 5");
else console.log("a !== 5");
->1
2let a = 10;
a === 5 && console.log("a === 5") || console.log("a !== 5");
11. Loop object
(*) Use this way really effective when object is 1 level object
use
for..in
1
2
3
4
5
6const object = {...};
for (let name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}use
array prototype function
(map, forEach..)
1 | const object = {...}; |
12. Clone object and array use Spread
a. Clone object:
1
2
3let obj = {a: 1, b: 2};
let obj2 = {...obj};
console.log(obj2); // -> {a: 1, b: 2};
b. Clone array:
1
2
3let arr = [1, 2];
let arr2 = [...arr];
console.log(arr2); // => [1, 2];
13. Join Array
1 | let one = ['a', 'b', 'c'] |
14. Set key from variable
1 | let myKey = 'key3'; |
->1
2
3
4
5
6
7let myKey = 'key3';
let obj = {
key1: 'One',
key2: 'Two',
[myKey]: 'Three'
};
console.log(obj); // -> {key1: "One", key2: "Two", key3: "Three"}
15. Cast value
1 | if (variable1 !== null || variable1 !== undefined || variable1 !== '') { |
->1
const variable2 = variable1 || 'new';
16. Object Property
1 | const obj = { x:x, y:y }; |
->1
const obj = { x, y };
17. Method
1 | var obj = { |
->1
2
3
4
5
6
7
8var obj = {
foo() {
/* code */
},
bar() {
/* code */
}
};
18. Parse Int (*) be careful
1 | let a = '123', b = '123a'; |
19. Verify variable (cast to boolean)
6 fasly value: false, null, 0, '', undefined, NaN
will cast to false
else cast to true
1
2
3if(typeof a !== 'undefined' && a !== null){
//
}
->1
2
3if(!!a){
}
20. Rest và spread
a. Rest: represents the rest: [phần còn lại] of function
, array
or object
with variable name1
2
3const [first, second, ...others] = [1, 2, 3, 4, 5]
console.log(first, second, others)
// 1 2 [3, 4, 5]
We can use rest to define a function flexible like bellow:1
2
3const foo = (...args) => console.log('You passed', args)
console.log(foo(1, 2, 3)) // You passed[ 1, 2, 3 ]
const bar = (x, y, ...rest) => console.log(rest, x, y)
(*) args
difference to arguments
:
args
is normal array
arguments
is default in a function, an object like Array
b. Spread: represents the object
or array available
with variable name
replace
.concat()
1
2
3
4
5
6
7const arr = [3, 4, 5]
const newArr = [1, 2, ...arr, 6]
console.log(newArr) // [1, 2, 3, 4, 5, 6]
const head = [1, 2]
const tail = [3, 4, 5]
console.log([...head, ...tail]) // [1, 2, 3, 4, 5]replace
.apply()
1
2
3
4const mul = (x, y, z) => x * y * z
const params = [1, 2, 3]
// mul.prototype.apply(null, params)
mul(...params)replace
.asign()
1
2
3
4
5
6
7
8
9
10const user = { name: 'John' }
// ES5
const userWithAgeEs5 = Object.assign({}, user, { age: 21 })
// With spread
const userWithAge = { ...user, age: 21 }
console.log(userWithAge) // { name: 'John', age: 21 }
// bonus rest detruct
const { name, ...others } = userWithAge
console.log(others) // { age: 21 }
21. Create & set key by variable
1 | const attr = 'foo' |
22. Deduplicated item in array
1 | const a = ['red', 'blue', 'sweet', 'red', 'you'] |
23. Number to character
1 | console.log('0123456789'.split('').map(no => String.fromCharCode(65 + +no)))//["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] |
24. Fast way Math.floor
1 | //similar way |