Logo

dev-resources.site

for different kinds of informations.

10 JavaScript Snippets That Will Save You Hours of Coding

Published at
1/9/2025
Categories
javascript
tutorial
frontend
webdev
Author
Maulik Paghdal
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)
  );
};

2. Copy to Clipboard

Quickly copy text to the clipboard without using external libraries:

const copyToClipboard = (text) => {  navigator.clipboard.writeText(text); };

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);

4. Flatten a Multi-Dimensional Array

Convert a nested array into a single-level array:

const flattenArray = (arr) => arr.flat(Infinity);

5. Get Unique Values in an Array

Remove duplicates from an array:

const uniqueValues = (array) => [...new Set(array)];

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')}`;

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

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;

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);

10. Generate a Random Integer

Generate a random number within a range:

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

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.

Featured ones: