10 Essential JavaScript Code Snippets for Every Developer
Shshank

Shshank @shshank

About: A coding soul

Location:
India
Joined:
May 16, 2018

10 Essential JavaScript Code Snippets for Every Developer

Publish Date: Sep 3 '23
11 7

1. Debounce Function: Prevents a function from being called too frequently, especially useful for handling user input.

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

2. Copy to Clipboard:

Allows you to copy text to the clipboard.

const copyToClipboard = (text) => {
  const textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("copy");
  document.body.removeChild(textArea);
};
Enter fullscreen mode Exit fullscreen mode

3. Deep Clone an Object:

Creates a deep copy of an object.

const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

4. Random Number Generator:

Generates a random number within a specified range.

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

5. Check if Array Contains Duplicates:

Checks if an array contains duplicate elements.

const hasDuplicates = (arr) => new Set(arr).size !== arr.length;
Enter fullscreen mode Exit fullscreen mode

6. Capitalize the First Letter of a String:

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

7. Date Formatting:

Formats a JavaScript Date object into a human-readable string.

const formatDate = (date) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  return date.toLocaleDateString(undefined, options);
};
Enter fullscreen mode Exit fullscreen mode

8. Calculate Array Sum:

Calculates the sum of elements in an array.

const sumArray = (arr) => arr.reduce((acc, current) => acc + current, 0);
Enter fullscreen mode Exit fullscreen mode

9. Validate Email Address:

Checks if a given string is a valid email address.

const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
Enter fullscreen mode Exit fullscreen mode

10. Fetch API Request:

Performs a simple HTTP GET request using the Fetch API.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

These JavaScript code snippets encompass various common tasks in web development and can be valuable additions to your projects. If you have any other helpful snippets to share, please feel free to contribute in the comments section, enhancing the utility of this thread.

Comments 7 total

  • Animesh_Singh
    Animesh_SinghSep 3, 2023

    Great post

  • Jon Randy 🎖️
    Jon Randy 🎖️Sep 3, 2023

    Your debounce function has a problem - you need to maintain the value of this or you will be calling the function in the wrong context in the timeout. Replace with func(...args) with func.apply(this, args).

    Also, there are many potential issues and gotchas using JSON.parse and JSON.stringify to deep clone an object. You are far better off using the built in function structuredClone - as long as you are not worried about Internet Explorer support.

    • Shshank
      ShshankSep 3, 2023

      thank you pointing this.

  • Parzival
    Parzival Sep 3, 2023

    Useful, thanks.

  • Idan Refaeli
    Idan RefaeliSep 3, 2023

    Deep cloning the way you mentioned may cause some problems in some scenarios.
    I would recommend using structuredClone() global function which is now available on all the popular browsers and also on Node.js & Deno runtimes.
    Or simply use Lodash's cloneDeep() function.

    • Shshank
      ShshankSep 3, 2023

      Thanks for mentioning

  • TechnologyMoment
    TechnologyMomentSep 3, 2023

    Liked this article!

Add comment