JavaScript remains one of the most widely used languages in modern development. Having a reliable set of reusable code snippets saves time, improves code clarity, and speeds up daily development tasks. This article collects 30 practical JavaScript snippets that are useful in real-world scenarios across front-end applications, back-end utilities, and browser automation. Each snippet includes a brief explanation and a realistic use case.
1. Utility Snippets
1. Random Number in Range
Generates an integer between two values.
Use case: random IDs, shuffling UI items.
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2. Check for Empty Value
Simple check for null, empty string, or empty array.
Use case: form validation, API checks.
const isEmpty = val => val == null || val === '' || (Array.isArray(val) && !val.length);
3. Deep Clone Object
Avoids reference mutations in state.
Use case: cloning objects before modifying them.
const deepClone = obj => JSON.parse(JSON.stringify(obj));
2. DOM Snippets
4. Add / Remove Class
Useful for UI state changes.
const addClass = (el, cls) => el.classList.add(cls);
const removeClass = (el, cls) => el.classList.remove(cls);
5. Create Element with Text
const createEl = (tag, content) => {
const el = document.createElement(tag);
el.textContent = content;
return el;
};
6. Smooth Scroll to Element
const scrollToEl = selector =>
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
3. Array & Object Snippets
7. Unique Array Values
const unique = arr => [...new Set(arr)];
8. Group by Property
Used in dashboards, reports, table data.
const groupBy = (arr, key) =>
arr.reduce((res, item) => {
(res[item[key]] = res[item[key]] || []).push(item);
return res;
}, {});
9. Merge Two Objects
const merge = (a, b) => ({ ...a, ...b });
10. Flatten an Array
const flatten = arr => arr.reduce((acc, val) => acc.concat(val), []);
4. String & Number Snippets
11. Capitalize First Letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
12. Mask Email
const maskEmail = email =>
email.replace(/(.{2}).+(@.+)/, '$1***$2');
13. Format Number as Currency
const toCurrency = (num, locale = 'en-US', currency = 'USD') =>
new Intl.NumberFormat(locale, { style: 'currency', currency }).format(num);
14. Reverse a String
const reverseStr = str => [...str].reverse().join('');
5. Browser & Storage Snippets
15. LocalStorage Helper
const storage = {
get: key => JSON.parse(localStorage.getItem(key)),
set: (key, val) => localStorage.setItem(key, JSON.stringify(val)),
remove: key => localStorage.removeItem(key)
};
16. Detect Dark Mode
const isDarkMode = () => window.matchMedia('(prefers-color-scheme: dark)').matches;
17. Copy to Clipboard
const copy = text => navigator.clipboard.writeText(text);
6. Date & Time Snippets
18. Days Between Dates
const daysBetween = (d1, d2) =>
Math.ceil(Math.abs(new Date(d2) - new Date(d1)) / 86400000);
19. Format Date
const formatDate = (date, locale = 'en-US') =>
new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: 'numeric' })
.format(new Date(date));
20. Relative Time
const timeAgo = date => {
const diff = Math.floor((Date.now() - new Date(date)) / 1000);
const units = { year: 31536000, month: 2592000, day: 86400, hour: 3600, min: 60 };
for (const [k, v] of Object.entries(units)) {
const val = Math.floor(diff / v);
if (val >= 1) return `${val} ${k}${val > 1 ? 's' : ''} ago`;
}
return 'just now';
};
7. Fetch & API Snippets
21. Fetch JSON Helper
const fetchJSON = async (url, options = {}) => {
const res = await fetch(url, options);
if (!res.ok) throw new Error('Request failed');
return res.json();
};
22. Retry Fetch
const fetchRetry = async (url, retries = 3) => {
try { return await fetch(url); }
catch (err) {
return retries ? fetchRetry(url, retries - 1) : Promise.reject(err);
}
};
23. Fetch with Timeout
const fetchTimeout = (url, ms) =>
Promise.race([
fetch(url),
new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms))
]);
8. Performance Snippets
24. Debounce
const debounce = (fn, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
25. Throttle
const throttle = (fn, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
};
26. Memoize
const memoize = fn => {
const cache = {};
return arg => cache[arg] ?? (cache[arg] = fn(arg));
};
9. Node.js Snippets
27. Get Env Variable with Default
const env = (key, fallback = '') => process.env[key] || fallback;
28. Simple HTTP Server
const http = require('http');
http.createServer((_, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Server running');
}).listen(3000);
29. Read JSON File
const fs = require('fs');
const readJSON = path => JSON.parse(fs.readFileSync(path, 'utf8'));
10. Modern ES6+ Snippets
30. Optional Chaining with Default
const city = user?.address?.city ?? 'Unknown';
Conclusion
A concise set of reusable JavaScript snippets can significantly speed up development and help maintain cleaner code. The 30 examples above cover common needs across data manipulation, UI interactions, browser utilities, date formatting, and API handling. Keeping such snippets accessible - whether in a personal cheat sheet or integrated into an editor - allows developers to work more efficiently and avoid re-solving the same problems repeatedly.