4 JavaScript Code Snippets to Solve Your Everyday Problems π»
Kaleem Elahi
Posted on June 17, 2021
Let's start π
1) How To Get A Random Number In A Range of Values
const getRandomIntInRange = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
getRandomIntInRange(2, 20) // 8
2) How To Create A Random String
const generateRandomString = (length) =>
Math.random().toString(20).substr(2,length);
generateRandomString(5) // 9d8c2
3) How To Set A Value If The Variable is null or Undefined
const foo = null ?? 'default string';
const baz = ?? 42;
foo; // default string
baz; // 0
4) How To Implement A Sleep Function
const sleep = (ms) => new Promise( (resolve) => setTimeout(resolve, ms));
(async() > {
console.log(new Date()) // ? Mon Jun 14 2021 01:35:25 GMT+0300
await sleep(3000);
console.log(new Date()) // ? Mon Jun 14 2021 01:35:28 GMT+0300
})()
.
.
.
.
Add comments if you get stuck or find any issue implementing it
π πͺ π
π©
Kaleem Elahi
Posted on June 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.