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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

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