Created by CyanHall.com on 11/07/2020 , Last updated: 04/30/2021.
πŸ‘‰Β Β github shields Star me if it’s helpful.

1. Destructuring Assignment

    let [first, last] = ['Cyan', 'Hall']
// or
let {first, last} = {
  first: 'Cyan',
  last: 'Hall'
}
  

2. String methods

    "CyanHall".includes("yan") // true
"CyanHall".startsWith("Cyan") // true
"CyanHall".endsWith("Hall") // true
'C:yan:Hall'.split(':') // ["C", "yan", "Hall"]
parseFloat("123").toFixed(2) // "123.00"
  

3. Arrow function

    const getName = user => user.name
const funcName = name => {
  // do something
  return name
}
  

4. Array methods

    const numbers = [1, 2, 3]
numbers.map(n => n * 2) // [2, 4, 6]
numbers.filter(n => n % 2 === 0) // [2]
numbers.reduce((prev, next) => prev + next, 0) // 6
numbers.find(n => n > 2) // 3
  

5. Array manipulation

    // Delete at index
array.splice(index, 1)

// Insert at index
array.splice(index, 0, newItem)

// check exist
[1, 2, 3].includes(3) // true

// 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]
  

6. Spread operator

    const array1 = [1, 2]
const array2 = [...array1, 3, 4] // [1, 2, 3, 4]

const funcName = (x, ...params) => {
  console.log(x)
  console.log(params)
}

funcName(1, 2, 3, 4)
// 1
// [2, 3, 4]
  

7. Object spread

    const options = {
  ...defaults,
  show: true
}
  

8. Array spread

    const array3 = [
  ...array1,
  ...array2,
  'newItem'
]
  

9. Iterate

    for (const i of [1, 2, 3]) {
  console.log(i)
}
// 1
// 2
// 3

for (const [index, value] of ['Cyan', 'Hall', '.com'].entries()) {
  console.log(index, value)
}
// 0 "Cyan"
// 1 "Hall"
// 2 ".com"

const obj = {part1: 'Cyan', part2: 'Hall', part3: '.com'};
for (const key in obj) {
  console.log(key, obj[key])
}
// or
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}
// part1 Cyan
// part2 Hall
// part3 .com
  

10. 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(() => {
    // ...
  })
  

11. 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
  // ...
})
  

12. Async-await

    const funcName = async () => {
  const data = await fetchData()
  return data
}

await funcName()
  

13. Generator

    function * countdown(n) {
  for (let i = n; i > 0; --i) {
    yield i
  }
}
[...countdown(3)] // [ 3, 2, 1 ]

let gen = countdown(3)
gen.next() // 3
gen.next() // 2
  

14. Browser

    encodeURIComponent() // Encodes a URI into UTF-8
decodeURIComponent() // Decodes
  

15. window

    const formData = new window.FormData()
formData.append('file', data)

window.localStorage.getItem(key)
window.localStorage.setItem(key, data)

window.location.origin // "https://www.cyanhall.com"
window.location.hostname // "www.cyanhall.com"
window.location.href // "https://www.cyanhall.com/posts/notes/8.javascript-cheatsheet/"

window.open("https://www.cyanhall.com")

window.addEventListener('resize', resizeHandler)
window.removeEventListener('resize', resizeHandler)
  

16. XMLHttpRequest

    // Download excel file
const xhr = new window.XMLHttpRequest()
const applicationType = 'application/vnd.ms-excel; charset=UTF-8'
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new window.Blob([this.response], { type: applicationType })
    let downloadUrl = window.URL.createObjectURL(blob)
    let a = document.createElement('a')
    a.href = downloadUrl
    a.download = fileName
    a.click()
  }
}
xhr.onreadystatechange = e => {
  if (xhr.readyState === 4) {
    // 
  } else if (xhr.readyState === 3) {
    //
  })
}
xhr.send()
  

17. Email Validation

    // From https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(email) {
  if (email === '') {
    return true
  }
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
  

1. Destructuring Assignment

    let [first, last] = ['Cyan', 'Hall']
// or
let {first, last} = {
  first: 'Cyan',
  last: 'Hall'
}
  

3. Arrow function

    const getName = user => user.name
const funcName = name => {
  // do something
  return name
}
  

5. Array manipulation

    // Delete at index
array.splice(index, 1)

// Insert at index
array.splice(index, 0, newItem)

// check exist
[1, 2, 3].includes(3) // true

// 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]
  

7. Object spread

    const options = {
  ...defaults,
  show: true
}
  

9. Iterate

    for (const i of [1, 2, 3]) {
  console.log(i)
}
// 1
// 2
// 3

for (const [index, value] of ['Cyan', 'Hall', '.com'].entries()) {
  console.log(index, value)
}
// 0 "Cyan"
// 1 "Hall"
// 2 ".com"

const obj = {part1: 'Cyan', part2: 'Hall', part3: '.com'};
for (const key in obj) {
  console.log(key, obj[key])
}
// or
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}
// part1 Cyan
// part2 Hall
// part3 .com
  

11. 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
  // ...
})
  

13. Generator

    function * countdown(n) {
  for (let i = n; i > 0; --i) {
    yield i
  }
}
[...countdown(3)] // [ 3, 2, 1 ]

let gen = countdown(3)
gen.next() // 3
gen.next() // 2
  

15. window

    const formData = new window.FormData()
formData.append('file', data)

window.localStorage.getItem(key)
window.localStorage.setItem(key, data)

window.location.origin // "https://www.cyanhall.com"
window.location.hostname // "www.cyanhall.com"
window.location.href // "https://www.cyanhall.com/posts/notes/8.javascript-cheatsheet/"

window.open("https://www.cyanhall.com")

window.addEventListener('resize', resizeHandler)
window.removeEventListener('resize', resizeHandler)
  

17. Email Validation

    // From https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(email) {
  if (email === '') {
    return true
  }
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
  

2. String methods

    "CyanHall".includes("yan") // true
"CyanHall".startsWith("Cyan") // true
"CyanHall".endsWith("Hall") // true
'C:yan:Hall'.split(':') // ["C", "yan", "Hall"]
parseFloat("123").toFixed(2) // "123.00"
  

4. Array methods

    const numbers = [1, 2, 3]
numbers.map(n => n * 2) // [2, 4, 6]
numbers.filter(n => n % 2 === 0) // [2]
numbers.reduce((prev, next) => prev + next, 0) // 6
numbers.find(n => n > 2) // 3
  

6. Spread operator

    const array1 = [1, 2]
const array2 = [...array1, 3, 4] // [1, 2, 3, 4]

const funcName = (x, ...params) => {
  console.log(x)
  console.log(params)
}

funcName(1, 2, 3, 4)
// 1
// [2, 3, 4]
  

8. Array spread

    const array3 = [
  ...array1,
  ...array2,
  'newItem'
]
  

10. 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(() => {
    // ...
  })
  

12. Async-await

    const funcName = async () => {
  const data = await fetchData()
  return data
}

await funcName()
  

14. Browser

    encodeURIComponent() // Encodes a URI into UTF-8
decodeURIComponent() // Decodes
  

16. XMLHttpRequest

    // Download excel file
const xhr = new window.XMLHttpRequest()
const applicationType = 'application/vnd.ms-excel; charset=UTF-8'
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new window.Blob([this.response], { type: applicationType })
    let downloadUrl = window.URL.createObjectURL(blob)
    let a = document.createElement('a')
    a.href = downloadUrl
    a.download = fileName
    a.click()
  }
}
xhr.onreadystatechange = e => {
  if (xhr.readyState === 4) {
    // 
  } else if (xhr.readyState === 3) {
    //
  })
}
xhr.send()
  


Maitained byΒ Cyanhall.com, Copy Rights @ CC BY-NC-SA 4.0