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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay