This content originally appeared on DEV Community and was authored by Software Developer
1. Generating a Random Number
let randomNum = Math.floor(Math.random() * maxNum);
2. Checking If an Object is Empty
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
3. Creating a Countdown Timer
function countdownTimer(minutes) {
let seconds = minutes * 60;
let interval = setInterval(() => {
if (seconds <= 0) {
clearInterval(interval);
console.log("Time's up!");
} else {
console.log(`${Math.floor(seconds / 60)}:${seconds % 60}`);
seconds--;
}
}, 1000);
}
4. Sorting an Array of Objects
function sortByProperty(arr, property) {
return arr.sort((a, b) => (a[property] > b[property]) ? 1 : -1);
}
5. Removing Duplicates from an Array
let uniqueArr = [...new Set(arr)];
6. Truncating a String
function truncateString(str, num) {
return str.length > num ? str.slice(0, num) + "..." : str;
}
7. Converting a String to Title Case
function toTitleCase(str) {
return str.replace(/\b\w/g, txt => txt.toUpperCase());
}
8. Checking If a Value Exists in an Array
let isValueInArray = arr.includes(value);
9. Reversing a String
let reversedStr = str.split("").reverse().join("");
10. Creating a New Array from an Existing Array
let newArr = oldArr.map(item => item + 1);
11. Debouncing Function Calls
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
12. Throttling Function Calls
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
if (!lastRan) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(this, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
13. Cloning an Object
const cloneObject = (obj) => ({ ...obj });
14. Merging Two Objects
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
15. Checking for Palindrome Strings
function isPalindrome(str) {
const cleanedStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
return cleanedStr === cleanedStr.split('').reverse().join('');
}
16. Counting Occurrences in an Array
const countOccurrences = (arr) =>
arr.reduce((acc, val) => (acc[val] ? acc[val]++ : acc[val] = 1, acc), {});
17. Getting the Day of the Year from a Date Object
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
18. Filtering Unique Values from an Array
const uniqueValues = arr => [...new Set(arr)];
19. Converting Degrees to Radians
const degreesToRads = deg => (deg * Math.PI) / 180;
20. Delaying Function Execution
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
21. Flattening a Nested Array
const flattenArray = arr => arr.flat(Infinity);
22. Getting a Random Item from an Array
const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];
23. Capitalizing the First Letter of a String
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
24. Finding the Max Value in an Array
const maxVal = arr => Math.max(...arr);
25. Finding the Min Value in an Array
const minVal = arr => Math.min(...arr);
26. Shuffling an Array
function shuffleArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}
27. Removing Falsy Values from an Array
const removeFalsy = arr => arr.filter(Boolean);
28. Generating a Range of Numbers
const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);
29. Checking if Two Arrays are Equal
const arraysEqual = (a, b) =>
a.length === b.length && a.every((val, i) => val === b[i]);
30. Checking if a Number is Even
const isEven = num => num % 2 === 0;
31. Checking if a Number is Odd
const isOdd = num => num % 2 !== 0;
32. Removing Whitespace from a String
const removeSpaces = str => str.replace(/\s+/g, '');
33. Checking If a String is JSON
function isJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
34. Deep Cloning an Object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
35. Checking if a Number is Prime
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
36. Finding Factorial of a Number
const factorial = num =>
num <= 1 ? 1 : num * factorial(num - 1);
37. Getting Current Timestamp
const timestamp = Date.now();
38. Formatting Date as YYYY-MM-DD
const formatDate = date => date.toISOString().split('T')[0];
39. Generating UUID (Simple)
const uuid = () =>
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
40. Checking if an Object has a Property
const hasProp = (obj, key) => key in obj;
41. Getting Query Parameters from URL
const getQueryParams = url =>
Object.fromEntries(new URLSearchParams(new URL(url).search));
42. Escaping HTML Special Characters
const escapeHTML = str =>
str.replace(/[&<>'"]/g, tag => ({
'&':'&','<':'<','>':'>',
"'":''', '"':'"'
}[tag]));
43. Unescaping HTML Special Characters
const unescapeHTML = str =>
str.replace(/&(amp|lt|gt|#39|quot);/g, match => ({
'&':'&','<':'<','>':'>',
''':"'", '"':'"'
}[match]));
44. Sleep Function using Promise
const sleep = ms => new Promise(res => setTimeout(res, ms));
45. Sum of Array Elements
const sumArray = arr => arr.reduce((a, b) => a + b, 0);
46. Average of Numbers in Array
const avgArray = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
47. Finding Intersection of Two Arrays
const intersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x));
48. Finding Difference of Two Arrays
const difference = (arr1, arr2) => arr1.filter(x => !arr2.includes(x));
49. Checking if All Elements are Equal
const allEqual = arr => arr.every(val => val === arr[0]);
50. Generating a Random Hex Color
const randomHexColor = () =>
'#' + Math.floor(Math.random()*16777215).toString(16);
This content originally appeared on DEV Community and was authored by Software Developer
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
Software Developer | Sciencx (2025-10-04T22:30:00+00:00) 50 Most Useful JavaScript Snippets. Retrieved from https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/
" » 50 Most Useful JavaScript Snippets." Software Developer | Sciencx - Saturday October 4, 2025, https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/
HARVARDSoftware Developer | Sciencx Saturday October 4, 2025 » 50 Most Useful JavaScript Snippets., viewed ,<https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/>
VANCOUVERSoftware Developer | Sciencx - » 50 Most Useful JavaScript Snippets. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/
CHICAGO" » 50 Most Useful JavaScript Snippets." Software Developer | Sciencx - Accessed . https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/
IEEE" » 50 Most Useful JavaScript Snippets." Software Developer | Sciencx [Online]. Available: https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/. [Accessed: ]
rf:citation » 50 Most Useful JavaScript Snippets | Software Developer | Sciencx | https://www.scien.cx/2025/10/04/50-most-useful-javascript-snippets-2/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.