Calculate percent Link to heading

const calculatePercent = (value, total) => Math.round((value / total) * 100)

Sort Elements By Certain Property Link to heading

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)

Count Number of Occurrences Link to heading

const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0)

Wait for a Certain Amount of Time Link to heading

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

Insert an Element at a Certain Position Link to heading

const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)]

Other JS tricks Link to heading

isInteger Link to heading

Number.isInteger(mynum)

Shorthand with AND Link to heading

let someBool = true;
const someFunction = () => {
    // some function code
}

// long code
if (someBool) {
    someFunction();
}

shortcode

someBool && someFunction()

Comma Operator Link to heading

In JavaScript, the comma(,) operator is used for evaluating each of its operands from left to right and returns the value of the last operand.

let count = 1
let ret = (count++, count)
console.log(ret)

In the above example, the value of the variable ret will be, 2 he most common usage of the comma(,) operator is to supply multiple parameters in a for loop.

for (var i = 0, j = 50; i <= 50; i++, j--) {}

Destructuring Link to heading

let [first, ...rest] = arrayOfsomesort

Get Query Params Link to heading

window.location.search

The search property returns the query string from the location URL. Here is an example URL: https://kokaruk.com?project=js. The location.search will return, ?project=js

We can use another useful interface called, URLSearchParams along with location.search to get the value of the query parameters.

let project = new URLSearchParams(location.search).get('project');

Output: js