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. querySelectorAll
returns all the nodes.
const classEle = document.getElementsByClassName('className')
cont idEle = document.getElementById('id')
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')
array methods
The forEach
executes a provided function once for each array element.
const colors = ['red','white','blue']
colors.forEach(color => console.log(color))
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
//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 }
)
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
//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
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)
//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)
}
})()
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
}
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'))
//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)
})()
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
Top comments (0)