10 Best JavaScript Snippets to Speed Up Your Development

JavaScript is the backbone of modern web development, and having a few handy code snippets in your toolkit can save you hours of coding time. Whether you’re working on dynamic UI components, data manipulation, or debugging, these snippets can simplify your workflow and make you a more productive developer.

In this post, we’ve compiled 10 of the best JavaScript snippets that every developer should know. Feel free to bookmark them or integrate them into your projects.


1. Copy Text to Clipboard

Quickly copy any text to the user’s clipboard without using external libraries.

javascriptCopyEditconst copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => console.log("Text copied!"))
    .catch((err) => console.error("Error copying text: ", err));
};

copyToClipboard("Hello World!");

Use case: Useful for “Copy Code” or “Copy URL” buttons on websites.


2. Check if an Object is Empty

This snippet checks if an object has any properties.

javascriptCopyEditconst isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty({})); // true

Use case: Helps validate API responses or form data.


3. Debounce Function

Debouncing limits how often a function executes, preventing performance issues.

javascriptCopyEditconst debounce = (func, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
};

const onResize = debounce(() => console.log("Resized!"), 300);
window.addEventListener("resize", onResize);

Use case: Perfect for search bars and window resize events.


4. Shuffle an Array

Randomize the elements of an array.

javascriptCopyEditconst shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
console.log(shuffleArray([1, 2, 3, 4, 5]));

Use case: Use in quizzes, product recommendations, or random image carousels.


5. Smooth Scroll to Top

Add a smooth scroll-to-top feature with just one line.

javascriptCopyEditconst scrollToTop = () => window.scrollTo({ top: 0, behavior: "smooth" });
scrollToTop();

Use case: Ideal for “Back to Top” buttons.


6. Generate a Random Hex Color

This snippet creates a random color in hex format.

javascriptCopyEditconst randomColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
console.log(randomColor());

Use case: Use for dynamic theme generators or fun UIs.


7. Truncate Text

Shorten a long string and add ellipsis.

javascriptCopyEditconst truncate = (str, length) =>
  str.length > length ? str.slice(0, length) + "..." : str;

console.log(truncate("This is a long sentence", 10));

Use case: Great for displaying previews of blog posts or product descriptions.


8. Detect Dark Mode Preference

Detect if the user prefers dark mode.

javascriptCopyEditconst isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode); // true or false

Use case: Automatically adjust your theme based on user preferences.


9. Scroll to an Element

Smoothly scroll to a specific element on the page.

javascriptCopyEditconst scrollToElement = (element) =>
  document.querySelector(element).scrollIntoView({ behavior: "smooth" });

scrollToElement("#section-id");

Use case: Useful for navigation menus and single-page apps.


10. Unique Array Values

Remove duplicates from an array.

javascriptCopyEditconst uniqueArray = (arr) => [...new Set(arr)];
console.log(uniqueArray([1, 2, 2, 3, 4, 4]));

Use case: Perfect for filtering data and removing redundant items.


Conclusion

These JavaScript snippets are small but powerful tools that can save you time and effort in everyday coding tasks. By incorporating these reusable pieces of code, you can boost your productivity and focus on building better user experiences.

Shopping Cart
  • Your cart is empty.
WhatsApp
Scroll to Top