← All Tools

⚡ JavaScript Cheat Sheet

Modern JS quick reference — 128+ snippets

Showing all snippets

Variables & Types

let x = 10
Block-scoped variable
const PI = 3.14
Constant (can't reassign)
var old = true
Function-scoped (avoid in modern JS)
typeof x
Check type: 'string', 'number', 'boolean', etc.
Array.isArray(arr)
Check if value is an array
Number('42')
Convert to number
String(42)
Convert to string
Boolean(0) // false
Falsy: 0, '', null, undefined, NaN, false
parseInt('42px') // 42
Parse integer from string
parseFloat('3.14') // 3.14
Parse float from string

Strings

`Hello ${name}`
Template literal (backticks)
str.length
String length
str.toUpperCase()
Convert to uppercase
str.toLowerCase()
Convert to lowercase
str.trim()
Remove whitespace from both ends
str.includes('sub')
Check if contains substring
str.startsWith('pre')
Check prefix
str.endsWith('.js')
Check suffix
str.indexOf('sub')
Find index of substring (-1 if not found)
str.slice(1, 5)
Extract substring
str.split(',')
Split into array
str.replace(/old/g, 'new')
Replace all occurrences
str.padStart(5, '0')
Pad start: '00042'
str.repeat(3)
Repeat string 3 times

Arrays

[1, 2, 3]
Create array
arr.push(4)
Add to end
arr.pop()
Remove from end
arr.unshift(0)
Add to beginning
arr.shift()
Remove from beginning
arr.length
Array length
arr.includes(2)
Check if contains value
arr.indexOf(2)
Find index of value
arr.find(x => x > 2)
Find first matching element
arr.findIndex(x => x > 2)
Find index of first match
arr.filter(x => x > 2)
Filter elements
arr.map(x => x * 2)
Transform each element
arr.reduce((sum, x) => sum + x, 0)
Reduce to single value
arr.forEach(x => console.log(x))
Iterate over elements
arr.some(x => x > 5)
True if any match
arr.every(x => x > 0)
True if all match
arr.sort((a, b) => a - b)
Sort numerically
arr.reverse()
Reverse in place
arr.flat()
Flatten nested arrays
[...arr1, ...arr2]
Spread: merge arrays
arr.slice(1, 3)
Extract portion (non-mutating)
arr.splice(1, 2)
Remove/insert elements (mutating)
Array.from({length: 5}, (_, i) => i)
Create [0,1,2,3,4]
[...new Set(arr)]
Remove duplicates

Objects

{ key: 'value' }
Create object
obj.key
Access property (dot notation)
obj['key']
Access property (bracket notation)
obj?.nested?.deep
Optional chaining (safe access)
obj.key ?? 'default'
Nullish coalescing
Object.keys(obj)
Get all keys as array
Object.values(obj)
Get all values as array
Object.entries(obj)
Get [key, value] pairs
{ ...obj1, ...obj2 }
Spread: merge objects
const { a, b } = obj
Destructure object
const { a: alias } = obj
Destructure with alias
const { a = 10 } = obj
Destructure with default
Object.assign({}, obj)
Shallow clone
structuredClone(obj)
Deep clone (modern)
delete obj.key
Delete property
'key' in obj
Check if key exists
Object.freeze(obj)
Make immutable

Functions

function greet(name) {}
Function declaration
const greet = (name) => {}
Arrow function
const add = (a, b) => a + b
Arrow function (implicit return)
function f(x = 10) {}
Default parameter
function f(...args) {}
Rest parameters
f(...arr)
Spread arguments
const fn = (a, b = a * 2) => {}
Default depends on other param
setTimeout(() => {}, 1000)
Delay execution by 1 second
setInterval(() => {}, 1000)
Repeat every 1 second

Promises & Async

new Promise((resolve, reject) => {})
Create promise
promise.then(val => {})
Handle resolved value
promise.catch(err => {})
Handle rejection
promise.finally(() => {})
Always runs
async function f() {}
Async function
const result = await promise
Wait for promise
Promise.all([p1, p2])
Wait for all (fails if any fails)
Promise.allSettled([p1, p2])
Wait for all (never rejects)
Promise.race([p1, p2])
First to settle wins
Promise.any([p1, p2])
First to resolve wins
try { await f() } catch(e) {}
Async error handling

DOM

document.getElementById('id')
Select by ID
document.querySelector('.class')
Select first match (CSS selector)
document.querySelectorAll('div')
Select all matches
el.textContent = 'text'
Set text content
el.innerHTML = '<b>bold</b>'
Set HTML content
el.setAttribute('class', 'active')
Set attribute
el.classList.add('active')
Add CSS class
el.classList.toggle('active')
Toggle CSS class
el.style.color = 'red'
Set inline style
el.addEventListener('click', fn)
Add event listener
el.remove()
Remove element from DOM
parent.appendChild(child)
Append child element
document.createElement('div')
Create new element

Fetch API

const res = await fetch(url)
GET request
const data = await res.json()
Parse JSON response
fetch(url, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } })
POST with JSON
res.ok
True if status 200-299
res.status
HTTP status code
res.headers.get('content-type')
Get response header

ES6+ Features

const [a, b, ...rest] = [1,2,3,4]
Array destructuring
for (const item of arr) {}
for...of loop
for (const [key, val] of map) {}
Iterate Map
new Map()
Key-value store (any key type)
new Set()
Unique values collection
Symbol('desc')
Unique identifier
class Dog { constructor(name) {} }
Class syntax
class Puppy extends Dog {}
Class inheritance
export default function() {}
Default export
import { func } from './module.js'
Named import
import func from './module.js'
Default import
a?.b?.c
Optional chaining
a ?? b
Nullish coalescing (null/undefined only)
a ||= b
Logical OR assignment
a ??= b
Nullish coalescing assignment

Useful One-liners

Math.max(...arr)
Max value in array
Math.min(...arr)
Min value in array
Math.floor(Math.random() * 10)
Random int 0-9
arr.sort(() => Math.random() - 0.5)
Shuffle array (simple)
JSON.parse(JSON.stringify(obj))
Deep clone (legacy)
new Date().toISOString()
Current ISO timestamp
Number(n).toFixed(2)
Format to 2 decimal places
Object.fromEntries(entries)
Convert entries to object
crypto.randomUUID()
Generate UUID (modern browsers)
\xF0\x9F\x92\x99 Tip\xF0\x9F\x93\x9A Get Bundle \x244.99