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);
  };
};
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

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);
};
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

3. Deep Clone an Object:

Creates a deep copy of an object.

const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

4. Random Number Generator:

Generates a random number within a specified range.

const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

5. Check if Array Contains Duplicates:

Checks if an array contains duplicate elements.

const hasDuplicates = (arr) => new Set(arr).size !== arr.length;
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

6. Capitalize the First Letter of a String:

const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

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);
};
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

8. Calculate Array Sum:

Calculates the sum of elements in an array.

const sumArray = (arr) => arr.reduce((acc, current) => acc + current, 0);
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

9. Validate Email Address:

Checks if a given string is a valid email address.

const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

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));
🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung 🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung

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)

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
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.

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
shshank profile image
Shshank •

thank you pointing this.

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
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.

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
shshank profile image
Shshank •

Thanks for mentioning

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
parzival_computer profile image
Parzival •

Useful, thanks.

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
animeshworkplace profile image
Animesh_Singh •

Great post

🔴 Live TV: shshank/ essential javascript code snippets for every developer ml - Jadwal Siaran Langsung
 
technologymoment profile image
TechnologyMoment •

Liked this article!