DEV Community

Huy Do
Huy Do

Posted on

JavaScript methods will help you code better

These JavaScript methods will help your daily job easier. I have not used these methods a lot, but I found out they are very handy when you are coding. They are query selector, array methods, restructuring, promise, error handling.

query selector
You can use getElementByClassName or getEelementById. But we can use querySelector to replace them.querySelector returns the first Element with the document that matches the specified selector. querySelectorAllreturns all the nodes.

const classEle = document.getElementsByClassName('className')
cont idEle = document.getElementById('id')
Enter fullscreen mode Exit fullscreen mode
const classEle = document.querySelector('className')
cont idEle = document.querySelector('#id')
// sub elements
const subEle = document.querySelector('.className > li')
// returns all nodes
const subEle = document.querySelectorAll('div')
Enter fullscreen mode Exit fullscreen mode

array methods
The forEach executes a provided function once for each array element.

const colors = ['red','white','blue']
colors.forEach(color => console.log(color))
Enter fullscreen mode Exit fullscreen mode

reduce gives you accumulator and value in the callback function.
accumulator doesn't have to be a number, it can be array, object

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
Enter fullscreen mode Exit fullscreen mode
//Counting instance of values of an object
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
console.log(countedNames)
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
)
Enter fullscreen mode Exit fullscreen mode

destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

//get propery of object
const listItem = {name: 'shirt', cost: 4}
const {cost} = listItem;
console.log(cost)  //4

//use destructuring as argument of function
// const listItem = {name: 'shirt', cost: 4}
function printCost(getCost) {
    console.log(getCost.cost)
}
printCost(listItem) 
//4
Enter fullscreen mode Exit fullscreen mode
//nested object and object destructuring
const clothesPrice = {
    shirts: {
        polo: 5,
        tShirt: 6
    }
}

const {shirts: {polo}} = clothesPrice
console.log(polo) //5

//destructor right afer creating the array
const arr = [3, 2, 6]

const[first] = arr.sort()
console.log(first) //2
Enter fullscreen mode Exit fullscreen mode

promise
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

//run multiple promises at the same time. It will give an array of results.  Some of these can be a failure, and it will handle the error.
const myURLs = [
  'https://amazon.com',
  'https://youtube.com',
  'https://unsplash.com/'
]
const requests = myURLs.map(url => fetch(url))
const responses = Promise.all(requests)
Enter fullscreen mode Exit fullscreen mode
//run promise one after the other.  You can use `async` and `await` inside `for of` or `forEach` loop

const myURLs = [
  'https://amazon.com',
  'https://youtube.com',
  'https://unsplash.com/'
]
(async () => {
  const responses = []

  myURLs.forEach(url => {
    const resp = await fetch(url)
    responses.push(resp)
  } 
})()
Enter fullscreen mode Exit fullscreen mode

error handling
You can use try catch block. catch in regular fetch or async await.

try {
  throw 'myException'; // generates an exception
}
catch (err) {
  // statements to handle any exceptions
  logMyErrors(err);    // pass exception object to error handler
}
Enter fullscreen mode Exit fullscreen mode
fetch('https://amazon.com')
  .then(res => {
     res.json().then(json => {
        console.log(json)
   })
   .catch(err => console.error('json failed'))
})
.catch(err => console.error('request failed'))
Enter fullscreen mode Exit fullscreen mode
//cleaner
(async () => {
  const resp = await fetch('https://amazon.com').catch(err => console(error(err))
  const json = await resp.json().catch(err => console.error(err))
  console.log('got json', json)
})()
Enter fullscreen mode Exit fullscreen mode

References
https://www.youtube.com/watch?v=_n8x8MhQo1k
https://developer.mozilla.org/enUS/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_e

Discussion (0)