Different ways to pass parameters to a setTimeout
const addNum = (a, b) => console.log(a + b); setTimeout(addNum, 1000, 2, 3) //result: 5 setTimeout(() => { addNum(2,3); },1000) //result: 5 setTimeout(addNum.bind(null, 2, 3), 1000); //result: 53 ways to get the Date and Time in milliseconds
new Date().getTime(); // 1576509862158 Date.now(); // 1576509862158 +new Date(); // 1576509862158function() declaration in ES5 and ES6
// old way ES5
function tomAndJerry(){
}
// Es6
tomAndJerry() => {
}
Caching the array.length in the loop
let array = new Array(le9);
for(let i = 0; i < array.length; i++){
// this loop will calculate array length in each iteration
}
for(let i = 0; length = array.length; i < array.length; i++){
// this loop will calculate array length only once
}
Different approaches to creating an HTML link
let myText = 'Click me please'
// usual way
`<a href="#">${myText}</a>`
// <a href="#">Click me please</a>
// Using link method
myText.link(#);
// <a href="#">Click me please</a>
Easily check the visibility of div or page
window.addEventListener('visiblitychange', ()=> {
// document => define any html element div, a, span
if(document.hidden){
console.log('div is hidden')
}else{
console.log('div is visible')
}
})
Check the data array or not? using isArray()
let array = [1,2,3,4]
let numb = 3
Array.isArray(array) // return true
Array.isArray(numb) // return false
Array.reduce()
It applies a function to each element in an array and reduces the array into a single element.
const arr = [5, 10, 15, 20, 25];
const result = arr.reduce((total, currentValue) => {
console.log(currentValue); // 5 10 15 20 25
return total+currentValue;
});
console.log(result)
//result 75
How to verify that a given argument is a number
isNumber = (n) => {
return !isNaN(parseFloat(n)) isFinite(n);
}
isNumber(4) // true
isNumber(4.4) // true
isNumber('4') // false
Generate a random set of alphanumeric characters
// genreate random aplhanumeric
generateRandomAlphaNum = len =>{
var rdmString='';
for(; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.Substr(0, len);
}
generateRandomAlphaNum(5) // result blphj
generateRandomAlphaNum(11) // result: uug4th6ie2h
generateRandomAlphaNum(8) // result: rimbe38x
I hope this will help your developing skills. If any queries feel free in below comment section. Have a great day!.
< Javascript trick part 2 Javascript tirck part 4 >
Please make sure your comments are readable.