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

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more β†’

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay