JavaScript Cheat Sheet

Modern JavaScript reference with ES6+, async/await, DOM manipulation, array methods, and common patterns. Copy-ready code snippets.

81 entries 8 sections

Variables

Syntax Description Example
Block-scoped constant (cannot reassign) const PI = 3.14159
Block-scoped variable (can reassign) let count = 0; count++;
Function-scoped variable (avoid in modern JS) var old = true;
Returns type as string typeof 42 → 'number'
Checks if object is instance of class [] instanceof Array → true
Intentional absence of value let x = null;
Variable declared but not assigned let x; // undefined
Not a Number (result of invalid math) Number('abc') → NaN

Strings

Syntax Description Example
Number of characters in string 'hello'.length → 5
Check if string contains substring 'hello'.includes('ell') → true
Check if string starts with s 'hello'.startsWith('he') → true
Extract part of string 'hello'.slice(1, 3) → 'el'
Split string into array 'a,b,c'.split(',') → ['a','b','c']
Replace first occurrence 'hi hi'.replace('hi','hey') → 'hey hi'
Replace all occurrences 'hi hi'.replaceAll('hi','hey') → 'hey hey'
Remove whitespace from both ends ' hi '.trim() → 'hi'
Convert to uppercase 'hello'.toUpperCase() → 'HELLO'
Pad start to length n '5'.padStart(3, '0') → '005'
Template literal with interpolation `Hello ${name}!`
Get char at index (supports negative) 'hello'.at(-1) → 'o'

Arrays

Syntax Description Example
Add item to end of array [1,2].push(3) → [1,2,3]
Remove and return last item [1,2,3].pop() → 3
Add item to start of array [2,3].unshift(1) → [1,2,3]
Remove and return first item [1,2,3].shift() → 1
Transform each element [1,2,3].map(x => x*2) → [2,4,6]
Keep elements that pass test [1,2,3].filter(x => x>1) → [2,3]
Reduce array to single value [1,2,3].reduce((a,b) => a+b, 0) → 6
Find first element matching condition [1,2,3].find(x => x>1) → 2
Index of first match [1,2,3].findIndex(x => x>1) → 1
True if any element passes test [1,2,3].some(x => x>2) → true
True if all elements pass test [1,2,3].every(x => x>0) → true
Flatten nested arrays [[1],[2,[3]]].flat(2) → [1,2,3]
Check if array contains value [1,2,3].includes(2) → true
Spread / concatenate arrays [...[1,2], ...[3,4]] → [1,2,3,4]
Create array from iterable Array.from('abc') → ['a','b','c']
Sort array (mutates) [3,1,2].sort((a,b) => a-b) → [1,2,3]
Sort without mutating (ES2023) [3,1,2].toSorted() → [1,2,3]
Deep clone array/object structuredClone([{a:1}])

Objects

Syntax Description Example
Object literal const user = { name: 'Jo', age: 30 }
Access property user.name → 'Jo'
Spread / shallow clone object const copy = { ...user }
Array of keys Object.keys({a:1,b:2}) → ['a','b']
Array of values Object.values({a:1,b:2}) → [1,2]
Array of [key, value] pairs Object.entries({a:1}) → [['a',1]]
Copy properties to target Object.assign({}, obj1, obj2)
Make object immutable Object.freeze({a:1})
Optional chaining (safe access) user?.address?.city
Nullish coalescing (null/undefined only) null ?? 'default' → 'default'
Destructuring assignment const { name, age } = user;

Functions

Syntax Description Example
Function declaration (hoisted) function greet() { return 'hi'; }
Arrow function expression const add = (a, b) => a + b;
Default parameters const greet = (name = 'World') => `Hi ${name}`
Rest parameters (collect args) const sum = (...nums) => nums.reduce((a,b)=>a+b)
Spread arguments Math.max(...[1,2,3]) → 3

Async

Syntax Description Example
Create resolved promise Promise.resolve(42).then(v => ...)
Create a promise new Promise((resolve) => setTimeout(resolve, 1000))
Async function declaration async function getData() { ... }
Wait for promise to resolve const data = await fetch(url)
Wait for all promises const [a, b] = await Promise.all([p1, p2])
Wait for all, even rejected await Promise.allSettled([p1, p2])
Make HTTP request const res = await fetch('/api/data')
Parse response as JSON const data = await res.json()
Error handling block try { await fn() } catch(e) { console.error(e) }

DOM

Syntax Description Example
Select first matching element document.querySelector('.btn')
Select all matching elements document.querySelectorAll('li')
Attach event listener btn.addEventListener('click', handleClick)
Modify CSS classes el.classList.toggle('active')
Get/set text content el.textContent = 'Hello'
Get/set HTML content el.innerHTML = '<b>Bold</b>'
Set HTML attribute el.setAttribute('disabled', true)
Set inline CSS style el.style.display = 'none'

ES6+

Syntax Description Example
Class declaration class Animal { constructor(name) { this.name = name } }
Class inheritance class Dog extends Animal { bark() {} }
Named import import { useState } from 'react'
Default export export default function App() {}
Named exports export { add, subtract }
Key-value collection (any key type) const m = new Map(); m.set('a', 1);
Collection of unique values new Set([1,2,2,3]) → {1,2,3}
Create unique identifier const id = Symbol('id')
Iterate over iterable values for (const item of arr) { ... }
Iterate over object keys for (const key in obj) { ... }

Frequently asked questions

What's the difference between == and ===?

== does type coercion before comparing (so '5' == 5 is true). === compares both value AND type without coercion ('5' === 5 is false). Always use === to avoid unexpected behavior. The same applies to != vs !==.

When should I use arrow functions vs regular functions?

Arrow functions are shorter and don't have their own 'this' - they inherit it from the surrounding scope. Use them for callbacks, array methods, and short functions. Use regular functions when you need 'this' binding (methods, constructors) or hoisting.

What is the difference between null and undefined?

undefined means a variable was declared but never assigned a value - JavaScript sets this automatically. null is an intentional assignment meaning 'no value.' Use null when you want to explicitly indicate emptiness. Both are falsy.

How does 'this' work in JavaScript?

In a regular function, 'this' refers to the object that called the function. In arrow functions, 'this' inherits from the enclosing scope. In the global scope, 'this' is the window object (or undefined in strict mode). Use .bind(), .call(), or .apply() to explicitly set 'this'.

What are closures?

A closure is a function that remembers variables from its outer scope even after the outer function has returned. Every function in JavaScript creates a closure. Common use cases: data privacy, factory functions, and callbacks that need to remember state.

What's the difference between map() and forEach()?

map() returns a new array with transformed elements - use it when you need the result. forEach() returns undefined and is used for side effects only (logging, DOM manipulation). map() is generally preferred because it's more functional and chainable.

Go from reference to real skills

Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.

Browse all courses