Last updated
JavaScript Snippet Library Examples
The JavaScript Snippet Library provides ready-to-use, tested code snippets for common programming tasks. Below are examples from the library's main categories.
Array Manipulation Snippets
// Remove duplicates from array
const unique = arr => [...new Set(arr)];
unique([1, 2, 2, 3, 3, 4]); // → [1, 2, 3, 4]
// Flatten nested array
const flatten = arr => arr.flat(Infinity);
flatten([1, [2, [3, [4]]]]); // → [1, 2, 3, 4]
// Group array by property
const groupBy = (arr, key) =>
arr.reduce((groups, item) => ({
...groups,
[item[key]]: [...(groups[item[key]] || []), item]
}), {});
groupBy([
{ name: 'Alice', dept: 'Engineering' },
{ name: 'Bob', dept: 'Marketing' },
{ name: 'Carol', dept: 'Engineering' }
], 'dept');
// → { Engineering: [{Alice}, {Carol}], Marketing: [{Bob}] }
// Array intersection
const intersection = (a, b) => a.filter(x => b.includes(x));
intersection([1, 2, 3, 4], [2, 4, 6]); // → [2, 4]
// Shuffle array (Fisher-Yates)
const shuffle = arr => {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
String Processing Snippets
// Truncate string with ellipsis
const truncate = (str, maxLen) =>
str.length > maxLen ? str.slice(0, maxLen - 3) + '...' : str;
truncate('Hello, World!', 8); // → "Hello..."
// Convert to camelCase
const toCamelCase = str =>
str.replace(/[-_\s]+(.)/g, (_, c) => c.toUpperCase());
toCamelCase('hello-world'); // → "helloWorld"
toCamelCase('foo_bar_baz'); // → "fooBarBaz"
// Convert to kebab-case
const toKebabCase = str =>
str.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
toKebabCase('helloWorld'); // → "hello-world"
toKebabCase('FooBarBaz'); // → "foo-bar-baz"
// Count word occurrences
const wordCount = str =>
str.trim().split(/\s+/).reduce((counts, word) => ({
...counts,
[word.toLowerCase()]: (counts[word.toLowerCase()] || 0) + 1
}), {});
wordCount('the cat sat on the mat');
// → { the: 2, cat: 1, sat: 1, on: 1, mat: 1 }
// Generate random string
const randomString = (len = 8) =>
Math.random().toString(36).substring(2, 2 + len);
randomString(6); // → "k3m9xp"
Date and Time Snippets
// Format date as YYYY-MM-DD
const formatDate = date =>
date.toISOString().split('T')[0];
formatDate(new Date()); // → "2024-01-15"
// Days between two dates
const daysBetween = (d1, d2) =>
Math.abs(Math.round((d2 - d1) / (1000 * 60 * 60 * 24)));
daysBetween(new Date('2024-01-01'), new Date('2024-01-15')); // → 14
// Add days to date
const addDays = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
addDays(new Date('2024-01-15'), 30); // → 2024-02-14
// Check if date is in the past
const isPast = date => date < new Date();
// Relative time (time ago)
const timeAgo = date => {
const seconds = Math.floor((new Date() - date) / 1000);
const intervals = [
[31536000, 'year'], [2592000, 'month'],
[86400, 'day'], [3600, 'hour'],
[60, 'minute'], [1, 'second']
];
for (const [secs, label] of intervals) {
const count = Math.floor(seconds / secs);
if (count >= 1) return `${count} ${label}${count > 1 ? 's' : ''} ago`;
}
return 'just now';
};
timeAgo(new Date(Date.now() - 3600000)); // → "1 hour ago"
DOM Manipulation Snippets
// Check if element is in viewport
const isInViewport = el => {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
);
};
// Smooth scroll to element
const scrollTo = el =>
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
// Copy text to clipboard
const copyToClipboard = text =>
navigator.clipboard.writeText(text);
// Detect device type
const isMobile = () => window.innerWidth < 768;
const isTablet = () => window.innerWidth >= 768 && window.innerWidth < 1024;
const isDesktop = () => window.innerWidth >= 1024;
// Get all query parameters
const getQueryParams = () =>
Object.fromEntries(new URLSearchParams(window.location.search));
// URL: ?name=Alice&age=30
// → { name: 'Alice', age: '30' }
Async Utility Snippets
// Debounce
const debounce = (fn, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
const debouncedSearch = debounce(search, 300);
// Throttle
const throttle = (fn, limit) => {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
return fn(...args);
}
};
};
const throttledScroll = throttle(handleScroll, 100);
// Retry with exponential backoff
const retry = async (fn, retries = 3, delay = 1000) => {
try {
return await fn();
} catch (err) {
if (retries === 0) throw err;
await new Promise(r => setTimeout(r, delay));
return retry(fn, retries - 1, delay * 2);
}
};
// Sleep / delay
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
await sleep(1000); // wait 1 second
// Run async tasks with concurrency limit
const asyncPool = async (limit, tasks) => {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = Promise.resolve().then(task);
results.push(p);
executing.add(p);
p.finally(() => executing.delete(p));
if (executing.size >= limit) await Promise.race(executing);
}
return Promise.all(results);
};
Object Utility Snippets
// Deep clone object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
// Deep merge objects
const deepMerge = (target, source) => {
const result = { ...target };
for (const key of Object.keys(source)) {
if (source[key] instanceof Object && !Array.isArray(source[key])) {
result[key] = deepMerge(target[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
return result;
};
// Pick specific keys from object
const pick = (obj, keys) =>
Object.fromEntries(keys.map(k => [k, obj[k]]));
pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // → { a: 1, c: 3 }
// Omit keys from object
const omit = (obj, keys) =>
Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
omit({ a: 1, b: 2, c: 3 }, ['b']); // → { a: 1, c: 3 }
Browse the full library by category or search by keyword to find the right snippet for your task. Each snippet includes browser compatibility notes and usage examples.