Code & computing / QUICK REFERENCE

JavaScript patterns: arrays, objects and async

Common modern JavaScript patterns for collections, objects, functions, promises, strings, and JSON.

56 entries

Values, functions and objects

Immutable binding
const rate = 0.2;

Const prevents rebinding but does not deep-freeze an object. [1][4]

Reassignable binding
let count = 0;

Let allows reassignment within a lexical block. [1][4]

Arrow function
const square = x => x*x;

One-expression arrow functions return the expression's value. [1][4]

Named function
function add(a,b){return a+b;}

Ordinary function declaration can be invoked by name. [1][4]

Default parameter
const say = (name='Guest') => name;

Default applies when the argument is undefined. [1][4]

Object destructure
const {id,name} = obj;

Extract object fields into named local variables. [1][4]

Rename field
const {id:recordId} = obj;

Bind a property to a different identifier. [1][4]

Optional chaining
obj?.profile?.name

Stop safely at a nullish intermediate object. [1][4]

Nullish fallback
obj.value ?? 0

Preserve zero, false and empty string rather than replacing them. [1][4]

Shallow clone
const copy = {...obj};

Spread copies top-level own enumerable properties. [1][4]

Object keys
Object.keys(obj)

Retrieve own enumerable string property names. [1][4]

Object values
Object.values(obj)

Retrieve own enumerable property values. [1][4]

Object entries
Object.entries(obj)

Return arrays of corresponding keys and values. [1][4]

Entries to object
Object.fromEntries([['a',1],['b',2]])

Convert pairs into ordinary object properties. [1][4]

Filter and transform arrays

Transform array
items.map(x => x*2)

Returns a new array after mapping each item. [2][1]

Filter array
items.filter(x => x.active)

Keeps only elements passing a condition. [2][1]

First matching item
items.find(x => x.id===target)

Returns the first matching value or undefined. [2][1]

Find index
items.findIndex(x => x.id===target)

Returns zero-based index or -1 if absent. [2][1]

Any item matches
items.some(x => x.active)

Checks whether at least one element passes. [2][1]

All items match
items.every(x => x.active)

Empty arrays satisfy every by definition. [2][1]

Sum numeric elements
items.reduce((sum,x)=>sum+x,0)

Accumulates with explicit initial zero. [2][1]

Flatten one level
items.flat()

Flattens one level of nested arrays by default. [2][1]

Flatten mapped lists
items.flatMap(x => x.children)

Concatenates one nesting level of mapped children. [2][1]

Deduplicate values
[...new Set(items)]

Retains first occurrence of each unique primitive. [2][1]

Sorted copy
items.toSorted((a,b)=>a-b)

New numeric ordering without mutating original array. [2][1]

Reversed copy
items.toReversed()

Returns a new reverse-order array. [2][1]

First three
items.slice(0,3)

Copies indexes zero through two without mutating. [2][1]

Map property
items.map(x => x.name)

Project the requested field from each item. [2][1]

Async calls and errors

Resolved promise
Promise.resolve(42)

Create an already-fulfilled promise. [3][1]

Successful callback
promise.then(value=>console.log(value))

Register a fulfillment callback. [3][1]

Failure callback
promise.catch(err=>console.error(err))

Register a rejection callback. [3][1]

Final cleanup
promise.finally(()=>cleanup())

Run a callback after either fulfillment or rejection. [3][1]

Await result
const result = await promise;

Use within async functions or top-level ES module. [3][1]

Define async function
async function load(){return 42;}

An async function always returns a promise. [3][1]

Call fetch
const response = await fetch('/api/data');

HTTP error statuses do not automatically reject fetch. [3][1]

Check HTTP status
if(!response.ok) throw new Error('HTTP '+response.status);

Explicit status check catches HTTP errors. [3][1]

Read JSON body
const data = await response.json();

Await decoding; invalid JSON rejects. [3][1]

Parallel promises
await Promise.all([loadA(),loadB()])

Promise.all rejects on the first rejection. [3][1]

Record every outcome
await Promise.allSettled([loadA(),loadB()])

Results include successful and rejected promises. [3][1]

First fulfilled
await Promise.any([loadA(),loadB()])

Returns earliest fulfillment or rejects if every promise fails. [3][1]

Catch async error
try{await task();}catch(err){console.error(err);}

Surround an awaited operation with exception handling. [3][1]

Explicit typed error
throw new TypeError('Expected a number');

TypeError carries diagnostic type and message. [3][1]

Strings, JSON and DOM

Join text
'Hello, ' + name

Simple string concatenation does not need a template literal. [1][4]

Trim space
input.trim()

Removes leading and trailing whitespace characters. [1][4]

Find a substring
input.includes('word')

Case-sensitive substring membership test. [1][4]

Number from text
Number('12.5')

Converts numeric strings; invalid input produces NaN. [1][4]

Check finite number
Number.isFinite(value)

Distinguishes finite numbers from strings and infinity. [1][4]

Parse JSON
JSON.parse('{"ok":true}')

Parse valid JSON; invalid syntax throws. [1][4]

Serialize JSON
JSON.stringify({ok:true})

Returns a JSON string for supported values. [1][4]

UTC timestamp
new Date().toISOString()

ISO 8601 timestamp in UTC. [1][4]

Epoch timestamp
Date.now()

Milliseconds since 1970-01-01T00:00:00Z. [1][4]

First DOM match
document.querySelector('.card')

Browser API returns first matching Element or null. [1][4]

All DOM matches
document.querySelectorAll('button')

Browser API returns a static NodeList. [1][4]

Register event callback
button.addEventListener('click',handleClick)

Browser only; handleClick must be defined. [1][4]

Read data attribute
element.dataset.id

Browser read of the data-id attribute as a string. [1][4]

Recognize array
Array.isArray(data)

Correct array test across JavaScript realms. [1][4]

Reserved placement, separate from reference controls. No ad network is active.

Updated ECMAScript · modern browser / Node 24

Sources

  1. JavaScript guide ↗
  2. Array reference ↗
  3. Promise reference ↗
  4. Object reference ↗