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);
};
};
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);
};
3. Deep Clone an Object:
Creates a deep copy of an object.
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
4. Random Number Generator:
Generates a random number within a specified range.
const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
5. Check if Array Contains Duplicates:
Checks if an array contains duplicate elements.
const hasDuplicates = (arr) => new Set(arr).size !== arr.length;
6. Capitalize the First Letter of a String:
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
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);
};
8. Calculate Array Sum:
Calculates the sum of elements in an array.
const sumArray = (arr) => arr.reduce((acc, current) => acc + current, 0);
9. Validate Email Address:
Checks if a given string is a valid email address.
const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
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));
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.
Great post