10 JavaScript Snippets That Will Save You Hours of Coding

By Maulik Paghdal

07 Jan, 2025

10 JavaScript Snippets That Will Save You Hours of Coding

JavaScript is a versatile programming language, but writing repetitive code can consume a lot of time. By leveraging handy code snippets, you can simplify common tasks, reduce redundancy, and save hours of development time.

Here are 10 JavaScript snippets every developer should know to improve efficiency and productivity.

1. Copy to Clipboard

Copying text to the clipboard is a frequent requirement in web applications. This snippet handles it easily:

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

Use Case:

Great for implementing copy buttons on web pages.

2. Debounce Function

Debouncing is useful to control the rate of execution, such as handling input events or window resize:

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

Use Case:

Prevent excessive API calls during rapid user input.

3. Deep Clone an Object

For creating a deep copy of an object without modifying the original, use:

function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

Use Case:

Useful in state management where immutability is required.

4. Check if an Element is in Viewport

Determine if an HTML element is visible in the viewport:

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

Use Case:

Trigger animations or lazy loading when an element enters the viewport.

5. Generate Random Hex Color

Quickly generate a random hex color code for dynamic styling:

function randomHexColor() {
  return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
}

Use Case:

Randomize background colors or themes.

6. Capitalize the First Letter of a String

Easily capitalize the first letter of any string:

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Use Case:

Format user input or display data with proper capitalization.

7. Flatten a Nested Array

Flattening deeply nested arrays becomes simple with recursion:

function flattenArray(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}

Use Case:

Handle data transformations where APIs return nested arrays.

8. Check if a Value is an Object

Quickly verify if a value is an object:

function isObject(value) {
  return value && typeof value === 'object' && value.constructor === Object;
}

Use Case:

Useful in type-checking scenarios during development.

9. Get a Query Parameter from URL

Retrieve query string parameters from a URL:

function getQueryParam(param) {
  const params = new URLSearchParams(window.location.search);
  return params.get(param);
}

Use Case:

Read URL parameters for dynamic content rendering.

10. Group Array Elements by Property

Organize array objects into groups based on a specific property:

function groupBy(array, key) {
  return array.reduce((acc, obj) => {
    const prop = obj[key];
    acc[prop] = acc[prop] || [];
    acc[prop].push(obj);
    return acc;
  }, {});
}

Use Case:

Aggregate data for reports or categorization.

Why Use These Snippets?

  1. Efficiency: Save time writing repetitive code.
  2. Readability: Keep your codebase clean and understandable.
  3. Reusability: Snippets can be used across multiple projects.

Topics Covered