DEV Community

Cover image for 4 JavaScript Code Snippets to Solve Your Everyday Problems 👻
Kaleem Elahi
Kaleem Elahi

Posted on • Edited on

4 JavaScript Code Snippets to Solve Your Everyday Problems 👻

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
Enter fullscreen mode Exit fullscreen mode

2) How To Create A Random String

const generateRandomString = (length) =>
Math.random().toString(20).substr(2,length);

generateRandomString(5) // 9d8c2
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
})()

Enter fullscreen mode Exit fullscreen mode

.
.
.
.

Add comments if you get stuck or find any issue implementing it

Top comments (0)