DEV Community

Cover image for 10 Essential JavaScript Code Snippets for Every Developer
Shshank
Shshank

Posted on

10 Essential JavaScript Code Snippets for Every Developer

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.

Top comments (7)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

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.

Collapse
 
shshank profile image
Shshank

thank you pointing this.

Collapse
 
idanref profile image
Idan Refaeli • Edited

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.

Collapse
 
shshank profile image
Shshank

Thanks for mentioning

Collapse
 
animeshworkplace profile image
Animesh_Singh

Great post

Collapse
 
parzival_computer profile image
Parzival

Useful, thanks.

Collapse
 
technologymoment profile image
TechnologyMoment

Liked this article!