DEV Community

Maulik Paghdal for Script Binary

Posted on • Originally published at scriptbinary.com

3

10 JavaScript Snippets That Will Save You Hours of Coding

JavaScript is a powerful language, but writing repetitive code can consume your time. These 10 handy JavaScript snippets will simplify common tasks and boost your productivity. Let’s dive in!


1. Check if an Element is in Viewport

Easily determine if an element is visible within the viewport:

const isInViewport = (element) => {
  const rect = element.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
};
Enter fullscreen mode Exit fullscreen mode

2. Copy to Clipboard

Quickly copy text to the clipboard without using external libraries:

const copyToClipboard = (text) => {  navigator.clipboard.writeText(text); };
Enter fullscreen mode Exit fullscreen mode

3. Shuffle an Array

Randomize the order of elements in an array with this one-liner:

const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

4. Flatten a Multi-Dimensional Array

Convert a nested array into a single-level array:

const flattenArray = (arr) => arr.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

5. Get Unique Values in an Array

Remove duplicates from an array:

const uniqueValues = (array) => [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

6. Generate a Random Hex Color

Create a random hex color with ease:

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
Enter fullscreen mode Exit fullscreen mode

7. Debounce a Function

Prevent a function from firing too often, ideal for search input:

const debounce = (func, delay) => {  let timeoutId;  return (...args) => {    clearTimeout(timeoutId);    timeoutId = setTimeout(() => func(...args), delay);  }; };
Enter fullscreen mode Exit fullscreen mode

8. Detect Dark Mode

Check if a user’s system is in dark mode:

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
Enter fullscreen mode Exit fullscreen mode

9. Capitalize the First Letter of a String

A simple snippet to capitalize the first letter:

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
Enter fullscreen mode Exit fullscreen mode

10. Generate a Random Integer

Generate a random number within a range:

const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
Enter fullscreen mode Exit fullscreen mode

Conclusion

These snippets are a great way to save time and effort in your JavaScript projects. Bookmark them or integrate them into your personal utility library!

Learn More

For more JavaScript tips and tricks, check out the original article on Script Binary.

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 full post →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free