DEV Community 👩‍💻👨‍💻

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

Posted on • Updated 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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!