Cheatsheets
JavaScript
32 entries
JavaScript
Modern JavaScript reference covering arrays, objects, async, DOM, and ES6+ features
32 commands
CommandDescriptionExample
arr.map(x => x * 2)
Create a new array by applying a function to each element
[1,2,3].map(x => x * 2) // [2,4,6]arr.filter(x => x > 0)
Create a new array with only elements that pass the test
[-1,0,3].filter(x => x > 0) // [3]arr.reduce((acc, x) => acc + x, 0)
Reduce an array to a single value by accumulation
[1,2,3].reduce((a, x) => a + x, 0) // 6arr.find(x => x.id === id)
Return the first element that satisfies the condition
users.find(u => u.id === 42)arr.some(x => x > 5)
Return true if at least one element passes the test
[1,3,7].some(x => x > 5) // truearr.every(x => x > 0)
Return true if all elements pass the test
[1,2,3].every(x => x > 0) // true[...arr1, ...arr2]
Concatenate arrays using the spread operator
[...names, ...extras]arr.flat(Infinity)
Flatten a nested array to any depth
[[1,[2]],3].flat(Infinity) // [1,2,3]Object.keys(obj)
Return an array of an object's own enumerable property keys
Object.keys({a:1, b:2}) // ['a','b']Object.values(obj)
Return an array of an object's own enumerable property values
Object.values({a:1, b:2}) // [1, 2]Object.entries(obj)
Return an array of [key, value] pairs from an object
Object.entries({a:1}) // [['a',1]]{ ...obj, key: 'val' }
Spread and override properties to create a new object
{ ...user, role: 'admin' }const { a, b } = obj
Destructure properties from an object into variables
const { name, age } = userObject.fromEntries(entries)
Create an object from an iterable of [key, value] pairs
Object.fromEntries([['a',1]]) // {a:1}str.includes('text')
Check if a string contains a substring
'hello world'.includes('world') // truestr.split(',').map(s => s.trim())
Split a string and trim whitespace from each part
'a, b, c'.split(',').map(s => s.trim())`Hello, ${name}!`
Template literal for string interpolation
`Total: ${price * qty}`str.replace(/old/g, 'new')
Replace all occurrences of a pattern in a string
'aabb'.replace(/a/g, 'x') // 'xxbb'document.querySelector('.btn')
Select the first element matching a CSS selector
document.querySelector('#submit')element.addEventListener('click', fn)
Attach an event handler to a DOM element
btn.addEventListener('click', handleClick)element.classList.toggle('active')
Toggle a CSS class on an element
menu.classList.toggle('open')element.setAttribute('data-id', '1')
Set a DOM attribute on an element
el.setAttribute('aria-hidden', 'true')async function fn() { const data = await fetch(url).then(r => r.json()); }
Async function using await to fetch and parse JSON
const res = await fetch('/api/users')Promise.all([p1, p2])
Run multiple promises in parallel and wait for all to resolve
await Promise.all([fetchA(), fetchB()])Promise.allSettled([p1, p2])
Wait for all promises regardless of whether they resolve or reject
await Promise.allSettled([p1, p2])const [a, b, ...rest] = arr
Array destructuring with rest element
const [first, ...rest] = [1,2,3]const fn = (x = 0) => x * 2
Arrow function with a default parameter
const greet = (name = 'world') => `Hi ${name}`import { fn } from './module.js'
Import a named export from an ES module
import { useState } from 'react'export default function() {}
Export a default function from a module
export default function App() {}const memoized = (fn) => { const cache = {}; return (x) => cache[x] ?? (cache[x] = fn(x)); }
Higher-order function that memoizes results of a function
const cachedFib = memoize(fib)fn.bind(thisArg, arg1)
Create a new function with a fixed 'this' context and optional preset args
const log = console.log.bind(console)setTimeout(() => {}, 0)
Schedule a callback to run asynchronously after the current stack clears
setTimeout(() => update(), 100)