filter(Boolean) Removes Falsy Values
filter(Boolean) drops every falsy entry, including 0 and empty strings; an explicit predicate keeps legal zeros and reads clearly at review time.
Page 5 of 9
filter(Boolean) drops every falsy entry, including 0 and empty strings; an explicit predicate keeps legal zeros and reads clearly at review time.
Move an item to a new index with two splice calls in place, or rebuild with slices immutably; same-slot moves and past-end targets stay predictable.
Collect parallel work under named keys with Promise.all over Object.values, then pair settled results back with Object.keys so responses land on their labels.
requestIdleCallback schedules non-urgent work for idle time with a timeout floor, and cancelIdleCallback drops the task before it ever runs.
Intercept anchor clicks and scroll the matching section into view with smooth behavior, then sync the hash without triggering a page jump.
Move repeated membership checks from Array.prototype.includes to a Set built once, turning every lookup into a hash hit with case normalized at the boundary.
Sparse array holes are skipped by forEach and preserved by map, read as undefined by spread and includes, and created by delete without shrinking length.
unref detaches a timer from the event loop so background heartbeats cannot keep the process alive after the real work has finished.
Listen for visibilitychange to pause background syncing while the tab is hidden and run one catch-up pass as soon as the page becomes visible again.
A poll loop that checks an AbortSignal between attempts exits promptly when the caller aborts, instead of sleeping through every remaining interval.
AbortSignal.any merges several cancellation sources into one signal, so a parent controller aborts a running loop the moment any source fires.
Contrast sequential awaits with ordered parallel completion: map launches every call immediately and yields promises you await by index later.
Read array tails with at() negative indexes, get undefined for out-of-range positions, and build ring rotation on top of the same bounds-safe access.
Overlay typed-array views on one ArrayBuffer: aliased writes, endian byte order, copied slices, and detached buffers after transfer().
copyWithin moves a slice inside the same array without changing its length, reading before writing so overlapping ranges behave like memmove.
new Array(n).fill(row) repeats one reference, so a write into any row mutates all of them; Array.from with a factory builds independent rows instead.
Array.from with a length shell and a map fn builds numeric sequences, expands strings by code points, and converts iterables with a transform.
Partition records into null-prototype buckets with Object.groupBy, then derive counts, per-bucket totals, and safe reads of missing buckets.
join coerces null and undefined to empty strings while other values go through String(); missing data becomes invisible separators unless mapped first.
map invokes the callback with (value, index, array), so a bare parseInt reference silently parses in radix 1 and 2; wrap it in an arrow or use Number.
reverse flips the array in place and returns the same reference, while toReversed returns a distinct reversed copy and leaves the source untouched.
Arrow callbacks reuse the this of their defining scope: plain function callbacks lose it in strict mode, arrow callbacks keep the surrounding object.
Async functions always return a Promise: plain values get wrapped, returned promises get adopted, and thrown errors surface as rejections.
map with an async callback collects promises, not values: Promise.all awaits the already-concurrent requests, while await inside for..of runs sequentially.
Mutate Int32Array cells across a SharedArrayBuffer with Atomics add, store, compareExchange, and sub, where every operation reports the observed previous value.
The value attribute seeds the DOM property but they diverge once code or a user edits it; serializing forms must read properties, not getAttribute strings.
Each await hands control back to the event loop, so concurrent tasks interleave and a read-modify-write spanning an await silently loses updates.
Use BigInt once integers exceed Number.MAX_SAFE_INTEGER: exact arithmetic, explicit conversions, and a TypeError when mixing the two types.
createObjectURL binds a Blob to a blob: URL that stays valid until revokeObjectURL releases it; repeat calls create distinct URLs and double revocation is safe.
call and apply invoke a borrowed method with explicit this (apply takes the argument array), while bind pins this and leading arguments once.
Class get/set accessors look like properties but run through the class: writes validate, reads derive, and read-only accessors reject assignment.
Run one-time class setup with static blocks: derived lookup tables build after static fields initialize, and multiple blocks execute in declaration order.
Mutate class names through classList instead of className strings: toggle accepts a force argument for three-way intent and replace swaps atomically.
navigator.clipboard.writeText needs a secure context and a user gesture; wiring it into a click handler with a caught failure keeps copy working visibly.
codePointAt reads full Unicode code points even for emoji that occupy two UTF-16 units, and fromCodePoint turns numeric points back into strings.
Print object arrays as aligned tables with console.table: an optional columns list hides noise, plain objects tabulate by keys, deep data flattens first.
crypto.getRandomValues fills typed arrays from a cryptographically secure source, throws QuotaExceededError past 65536 bytes, and suits tokens and sampling.
Model failures as custom error classes and dispatch with instanceof: context rides on instances, prototype chains match subclasses, unknown errors fall through.
Destructuring pulls values out with defaults for missing slots and rest for leftovers, covering arrays, objects, swaps, and function parameters.
dialog.showModal opens a native modal in the top layer, and a form with method=dialog closes it while writing the submitter button value into returnValue.
replaceChildren swaps a list's nodes in one call so rerenders are cheap, and textContent keeps untrusted strings inert instead of parsed markup.
textContent stores untrusted text as one inert text node, while the same string through innerHTML is parsed as markup and handler attributes come alive.
encodeURIComponent escapes reserved characters per query value while encodeURI keeps URI structure intact, so every value gets component encoding.
Object.entries turns a record into sortable pairs, and sorting plus slice plus fromEntries rebuilds it as a ranking without ever touching the original.
A click travels down from window to the target during capture, then bubbles back up; listening in the wrong phase changes which handlers run.
every and some validate arrays with short-circuit evaluation, so predicate calls stop at the first failing or passing element.
floor, trunc and ceil agree on positives but split directions on negatives, and Math.round ties go toward positive infinity, so bucket math must pick one.
for await over already-started promises handles each result one at a time in start order; await inside the loop body serializes the starts as well.
for-of honors break and continue to control the loop itself, while return inside forEach only skips one item and the iteration still completes.
Show that forEach ignores awaited callbacks and the caller returns before work finishes, then fix it with for...of or an explicit Promise.all collection.
requestSubmit runs validation and delivers invalid or submit events with e.submitter; form.submit() navigates silently, skipping both entirely.
getBoundingClientRect returns the rendered box in viewport coordinates including padding and border, the primitive for tooltips and droppables.
history.pushState changes the address bar and stores view state without reloading, and popstate hands that state back on back and forward.
map plus spread replaces the one matching record and keeps every other element at its original reference, so unchanged items stay referentially identical.
indexOf searches with strict equality so NaN is never found; includes uses SameValueZero and reports NaN hits, making it the right check for dirty data.
input fires for every keystroke while change waits until the value commits on blur, so debounced search and final validation hook different events.
Place nodes precisely with insertAdjacentElement: beforebegin, afterbegin, beforeend, and afterend hit all four sides of a target element.
Intl.Collator applies locale rules: Swedish orders å ä ö after Z, German folds Ö next to O, and the comparator plugs straight into sort().
Intl.DisplayNames turns language and region codes into localized labels for the chosen locale and returns unknown codes unchanged instead of throwing.
Turn duration objects into locale wording with Intl.DurationFormat: default, long, digital styles, other locales, and sparse spans with partial units.
Count user-perceived characters with Intl.Segmenter grapheme segmentation, and switch granularity to word for locale-aware token splitting.
Failed parses produce an Invalid Date whose getTime is NaN; engines even roll 2026-02-30 to March 2, so strict checks must round-trip through toISOString.
Compose map, filter, take, drop, and flatMap directly on generators: unbounded sources stay lazy and only consumed items are produced.
JSON.stringify silently drops undefined properties, functions, and symbols, and writes null for array slots, so round-trips lose those fields.
A toJSON method decides what JSON.stringify writes for a custom type, the same hook Date uses to emit its ISO string; parsing back yields plain objects only.
event.key is the layout-interpreted character while event.code is the physical key, so shortcuts survive keyboard layouts and IME composition states.
{ once: true } removes a listener after its first call and a signal option removes many at once on abort, replacing manual removeEventListener bookkeeping.
Map iterates in first-insertion order: re-setting a key keeps its slot, delete plus re-insert moves it to the end, and integer keys stay put unlike object keys.
Show that Map matches object keys by reference identity, so an equal-shaped clone misses, while primitive keys keep plain value-equality matching.
matchMedia reads the prefers-reduced-motion preference, so decorative animation durations collapse to zero for users who asked for less motion.
Compare Math.round, trunc, floor, and ceil on negatives and halves: round sends every .5 toward positive infinity, trunc cuts, floor and ceil pull apart.
querySelectorAll returns a static NodeList snapshot while el.children is a live HTMLCollection, so one remove() changes one length but not the other.
null is an explicitly assigned empty value while undefined marks missing values; === tells them apart even though == and default parameters collapse them.
Destructured options with ?? fall back only on null and undefined, so legitimate zero, empty string, and false survive where || would overwrite them.
The global isFinite coerces its argument first, so quoted numbers and null pass; Number.isFinite accepts only genuine finite numbers.
Number.isNaN and Number.isFinite skip the numeric coercion the global isNaN and isFinite apply, so only the real NaN value and real numbers pass.
toString(radix) renders integers in bases 2 to 36 and parseInt parses them back; negative numbers keep their sign and decimals expand beyond the point.
Object.assign and spread merge one level deep: overridden keys point to new objects while untouched nested objects stay shared with the source.
Object.is compares with SameValue semantics: NaN equals itself and minus zero differs from zero, where === collapses both distinctions.
Show that integer-like keys sort numerically before string keys, which follow insertion order, and that JSON.stringify keeps the same order.
Object.preventExtensions blocks new keys, seal also blocks deletions, freeze also blocks writes; sealed objects still accept value changes in place.
Optional chaining stops evaluating at the first nullish link and returns undefined, with ?.() covering missing methods and ?? supplying defaults.
Number rejects any extra characters while parseInt and parseFloat consume leading digits; explicit radix and isFinite checks keep numeric input parsing strict.
Keep pointer events flowing to one element with setPointerCapture: drags continue outside the bounds until releasePointerCapture or pointercancel.
Drive the Popover API from JavaScript: showPopover, hidePopover, and togglePopover flip :popover-open state, and the toggle event reports both states.
A rejection skips every then until the nearest catch, so one handler covers a whole chain and a returned value marks the chain recovered.
An async executor swallows its own rejection so the outer promise stays pending forever; keep executors synchronous and chain async work from them.
finally registers cleanup that runs on fulfillment and rejection alike, leaves the original result untouched, and keeps cleanup logic out of then and catch.
Promise.race settles as soon as the first promise settles, win or lose, so timeouts and hedged reads come from one combinator while losing tasks keep running.
Start async chains with Promise.try so sync throws become rejections: extra arguments pass straight to the function without an arrow wrapper.
Copy objects with Object.getOwnPropertyDescriptors and defineProperties so getters stay live instead of being invoked once by spread.
Object.create(null) removes the prototype chain, so user-controlled keys like constructor and toString resolve to your own data instead of inherited members.
reduce folds an array into one accumulator; the initial value guards empty arrays — without it an empty input throws, with it the seed returns.
reduceRight folds from the last element toward the first, which is exactly the shape of right-associative evaluation and right-to-left function composition.
Schedule paint-aligned work with requestAnimationFrame, cancel pending callbacks before the next frame, and count the frames that actually ran.
setInterval schedules each tick from the previous fire time, so loop delays accumulate into drift; self-scheduling setTimeout targets absolute boundaries.
Default sort compares elements as UTF-16 code unit strings, so numbers sort lexicographically; numeric order needs an explicit comparator.
slice copies a range and leaves the array untouched, while splice deletes or inserts in place and returns removed elements; mixing them corrupts shared data.
The sticky y flag anchors a regex at lastIndex so failed matches abort instead of skipping ahead, making it the right tool for cursor-based tokenizing.
stopPropagation still lets same-node listeners run and only blocks bubbling; stopImmediatePropagation cuts off later listeners on the same node too.