Destructuring Assignment:
let [first, last] = ['first name', 'last name']
// or
let {first, last} = {
first: 'first name',
last: 'last name'
}
String methods:
"hello".repeat(3) // hellohellohello
"hello".includes("ll") // true
"hello".startsWith("he") // true
"hello".padStart(8) // " hello"
"hello".padEnd(8) // "hello "
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")
Arrow function:
const getName = user => user.name
const funcName = name => {
// do something
return name
}
Array methods:
const numbers = [0, 1, 2, 3, 4, 5, 6]
const doubledNumbers = numbers.map(n => n * 2) // [0, 2, 4, 6, 8, 10, 12]
const evenNumbers = numbers.filter(n => n % 2 === 0) // [0, 2, 4, 6]
const sum = numbers.reduce((prev, next) => prev + next, 0) // 21
const greaterThanFour = numbers.find((n) => n > 4) // 5
Array manipulation:
// Delete at index
array.splice(index, 1)
// Insert at index
array.splice(index, 0, newItem)
// find index
[1, 2, 3].indexOf(3) // 2; return -1 if not found
// concat
let array3 = array1.concat(array2) // [1].concat([2]) is [1, 2]
// new array
let array4 = [1, 2, 3, 4, 5].slice(2, 4) // [3, 4]
Spread operator: ...
const arr1 = ["a", "b", "c"]
const arr2 = [...arr1, "d", "e", "f"] // ["a", "b", "c", "d", "e", "f"]
const funcName = (x, y, ...params) => {
console.log(x)
console.log(y)
console.log(params)
}
funcName("a", "b", "c", "d", "e", "f")
// "a"
// "b"
// ["c", "d", "e", "f"]
Object spread:
const options = {
...defaults,
show: true
}
Array spread
const users = [
...admins,
...guests,
'newUser'
]
Iterate:
for (let i of [1, 2, 3]) {
console.log(i)
}
// 1
// 2
// 3
for (let [index, value] of ['hi', 'hello', 'world'].entries()) {
console.log(index, value)
}
// 0 "hi"
// 1 "hello"
// 2 "world"
const obj = {key1: 'hi', key2: 'hello', key3: 'world'};
for (let key in obj) {
console.log(key, obj[key])
}
// or
for (let [key, value] of Object.entries(obj)) {
console.log(key, value)
}
// key1 hi
// key2 hello
// key3 world
Create promise:
const funcName = params => {
return new Promise((resolve, reject) => {
// ....
// do something
// if success
resolve(result)
// if fail
reject(error)
})
}
funcName('test')
.then(result => {
// ...
})
.catch(error => {
// ...
})
.finally(() => {
// ...
})
All promise:
let promises = []
// func1 and func2 returns a promise
promises.push(func1())
promises.push(func2())
Promise.all(promises).then(allResult => {
let [result1, resul2] = allResult
// ...
})
Async-await:
const funcName = async () => {
const user = await getUser()
return user
}
funcName()
.then(result => {
// ...
})
.catch(error => {
// ...
})
.finally(() => {
// ...
})
Generator:
function * downToOne(n) {
for (let i = n; i > 0; --i) {
yield i;
}
}
[...downToOne(5)] // [ 5, 4, 3, 2, 1 ]
//
let gen = downToOne(5)
gen.next() // 5
gen.next() // 4
#javascript #web-development