JavaScript Important Code Snippets
Production-ready JavaScript utilities — debounce, throttle, deep clone, shuffle, groupBy, flatten, dedupe, date formatting, and safe nested access with interview-ready callouts.
Introduction
A curated set of production-ready JavaScript snippets — each with runnable code, practical notes, performance guidance, and interview-ready answers. Use the quick index to jump to any utility.
Snippet Reference
Quick index
| # | Snippet | Description |
|---|---|---|
| 1 | Debounce | Wait until the user stops triggering an event before running the handler |
| 2 | Throttle | Ensure a function runs at most once per time window |
| 3 | Deep Clone | Create a fully independent copy of nested objects and arrays without mutating the original. |
| 4 | Shuffle Array Elements | Randomly reorder array elements using the Fisher–Yates algorithm for an unbiased shuffle. |
| 5 | Generate Unique Key | Create short unique identifiers for React list keys, temp IDs, and client-side tracking. |
| 6 | Group Array Elements by Key | Partition an array of objects into buckets keyed by a property value. |
| 7 | Flatten Nested Array | Convert a deeply nested array into a single flat array of values. |
| 8 | Remove Duplicates | Deduplicate primitive arrays with Set or object arrays by a specific key. |
| 9 | Format Date | Format dates for display using Intl.DateTimeFormat with locale-aware output. |
| 10 | Safe Access Helper | Read deeply nested properties from an object using a dot-path string without throwing on missing keys. |
1. Debounce
Wait until the user stops triggering an event before running the handler — ideal for search inputs and resize listeners.
// Debounce: wait until user stops typing for `delay` ms
function debounce(func, delay) {
console.log('In debounce...')
let timer // holds timeout id
return function (...args) {
clearTimeout(timer) // cancel previous pending call
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
const search = debounce((q) => console.log('Search for:', q), 500)
search('J')
search('Ja')
search('Jav')
search('Java')
// Only one console log: "Search for: Java" after 300ms2. Throttle
Ensure a function runs at most once per time window — ideal for scroll, resize, and mousemove handlers.
// Throttle: ensure func runs at most once per `limit` ms
function throttle(func, limit) {
let lastCall = 0
return function (...args) {
const now = Date.now()
if (now - lastCall >= limit) {
lastCall = now
func.apply(this, args)
}
}
}
// Usage
window.addEventListener(
'scroll',
throttle(() => {
console.log('throttled scroll event')
}, 200),
)3. Deep Clone
Create a fully independent copy of nested objects and arrays without mutating the original.
// Deep clone using structuredClone (modern browsers / Node 17+)
// structuredClone preserves Dates, RegExp, Maps, Sets, and doesn't run code.
function deepClone(obj) {
return structuredClone(obj)
}
// Simple fallback: JSON deep copy — works for plain objects (no Date/Map/Set/functions)
function deepCloneFallback(obj) {
return JSON.parse(JSON.stringify(obj))
}
// Usage
const original = { name: 'A', meta: { joined: new Date(), tags: ['js'] } }
const copy = typeof structuredClone === 'function' ? deepClone(original) : deepCloneFallback(original)
copy.meta.tags.push('node')
console.log(original.meta.tags) // original unaffected: ["js"]4. Shuffle Array Elements
Randomly reorder array elements using the Fisher–Yates algorithm for an unbiased shuffle.
// Fisher–Yates shuffle — unbiased random shuffle
function shuffle(array) {
const arr = [...array] // copy to avoid mutating original
for (let i = arr.length - 1; i > 0; i--) {
// pick random index from 0..i
const j = Math.floor(Math.random() * (i + 1))
// swap arr[i] and arr[j]
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
return arr
}
// Usage
const deck = [1, 2, 3, 4, 5, 6]
console.log(shuffle(deck)) // shuffled array5. Generate Unique Key
Create short unique identifiers for React list keys, temp IDs, and client-side tracking.
// Simple short id — not cryptographically secure, but okay for UI keys
function uniqueId() {
// toString(36) makes it shorter (0-9a-z)
return Math.random().toString(36).substring(2, 10)
}
// Use timestamp + random to reduce collision probability
function uniqueIdSafe() {
return `${Date.now().toString(36)}-${Math.random().toString(36).substring(2, 8)}`
}
// Node/browser crypto (secure)
function uniqueIdCrypto() {
// browser: crypto.getRandomValues; Node: require('crypto').randomBytes
return crypto.randomUUID() // modern API (UUID v4), if available
}
// Usage:
console.log(uniqueId()) // ex: "k9x3f8q0"
console.log(uniqueIdSafe()) // ex: "l8k3x-9f2t3p"
console.log(uniqueIdCrypto())6. Group Array Elements by Key
Partition an array of objects into buckets keyed by a property value.
// Group by key using reduce
function groupBy(arr, key) {
return arr.reduce((acc, item) => {
const groupKey = item[key]
// if group doesn't exist, init as array
if (!acc[groupKey]) acc[groupKey] = []
acc[groupKey].push(item)
return acc
}, {})
}
// Usage
const users = [
{ name: 'A', role: 'dev' },
{ name: 'B', role: 'pm' },
{ name: 'C', role: 'dev' },
]
console.log(groupBy(users, 'role'))
// For modern browsers and Node environment
const grouped = Object.groupBy(users, (user) => user.role)
console.log(grouped)7. Flatten Nested Array
Convert a deeply nested array into a single flat array of values.
// Recursive flatten — handles arbitrary nesting
function flatten(arr) {
return arr.reduce((flat, item) => {
if (Array.isArray(item)) {
return flat.concat(flatten(item))
}
return flat.concat(item)
}, [])
}
// Usage:
console.log(flatten([1, [2, [3, 4]], 5])) // [1,2,3,4,5]
console.log([1, [2, [3, 4]], 5].flat(Infinity))8. Remove Duplicates
Deduplicate primitive arrays with Set or object arrays by a specific key.
// Simple and fast using Set (preserves insertion order)
const removeDuplicates = (arr) => [...new Set(arr)]
// Usage
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])) // [1,2,3,4]
// For arrays of objects (by key)
function uniqueBy(arr, key) {
const seen = new Set()
return arr.filter((item) => {
const k = item[key]
if (seen.has(k)) return false
seen.add(k)
return true
})
}9. Format Date
Format dates for display using Intl.DateTimeFormat with locale-aware output.
// Format date using Intl.DateTimeFormat (reliable & localizable)
function formatDate(dateInput, locale = 'en-US', options = { year: 'numeric', month: 'short', day: 'numeric' }) {
const date = new Date(dateInput)
if (Number.isNaN(date.getTime())) return 'Invalid Date'
return new Intl.DateTimeFormat(locale, options).format(date)
}
// Usage
console.log(formatDate('2025-01-15')) // "Jan 15, 2025" (en-US)
console.log(formatDate('2025-01-15', 'en-GB')) // "15 Jan 2025"10. Safe Access Helper
Read deeply nested properties from an object using a dot-path string without throwing on missing keys.
// safeGet: read nested path safely, return fallback if path not present
function safeGet(obj, path, fallback = null) {
return (
path.split('.').reduce((acc, key) => {
return acc?.[key]
}, obj) ?? fallback
)
}
// Usage:
const user1 = {
id: 101,
name: 'Garima',
address: { city: 'Kolkata', pin: 700001 },
}
const user2 = {
id: 102,
name: 'Geeta',
// address missing (maybe from incomplete API)
}
console.log(safeGet(user1, 'address.city', 'Unknown City')) // "Kolkata"
console.log(safeGet(user2, 'address.city', 'Unknown City')) // "Unknown City"
console.log(safeGet(user2, 'preferences.theme', 'light')) // "light"
// Alternative short using optional chaining directly. But safeGet is handy when path is dynamic (string).
const city = user2?.address?.city ?? 'Unknown City'Subscribe to my newsletter
Stay up to date and get notified when I share new contents.
No spam ever, unsubscribe anytime