Skip to main content
← All cheat sheets
πŸ“œ

JavaScript Cheat Sheet

A quick-reference JavaScript cheat sheet covering variables, arrays, objects, functions, and more.

Variables & Types

let count = 0;Block-scoped, reassignable variable.
const PI = 3.14;Block-scoped constant; cannot be reassigned.
typeof valueReturns the type as a string, e.g. 'number'.
let x = null;Intentional absence of any value.
let y;Declared but unassigned: value is undefined.
Array.isArray(value)True if value is an array.
Number.isNaN(value)Reliable check for NaN.

Strings

'Hello, ' + nameConcatenate strings with the + operator.
str.lengthNumber of characters in the string.
str.toUpperCase()Returns an uppercased copy.
str.includes('foo')True if the substring is present.
str.slice(0, 5)Extract a substring by index range.
str.split(',')Split a string into an array by a separator.
str.trim()Remove whitespace from both ends.
str.replace('a', 'b')Replace the first match with a new value.

Numbers & Math

parseInt('42', 10)Parse an integer from a string in base 10.
parseFloat('3.14')Parse a floating-point number from a string.
(1.005).toFixed(2)Format a number to a fixed number of decimals.
Math.round(4.6)Round to the nearest integer.
Math.max(1, 2, 3)Largest of the given numbers.
Math.floor(Math.random() * 10)Random integer from 0 to 9.
Math.abs(-5)Absolute value of a number.
10 % 3Modulo: remainder of a division (1).

Arrays

const arr = [1, 2, 3];Create an array literal.
arr.lengthNumber of elements in the array.
arr.push(4)Append an item to the end; returns new length.
arr.pop()Remove and return the last item.
arr.indexOf(2)Index of the first matching element, or -1.
arr.includes(2)True if the array contains the value.
arr.slice(1, 3)Shallow copy of a portion of the array.
arr.join('-')Combine elements into a string.

Array Methods

arr.map(x => x * 2)Transform each element into a new array.
arr.filter(x => x > 2)Keep only elements that pass the test.
arr.reduce((sum, x) => sum + x, 0)Reduce to a single accumulated value.
arr.forEach(x => console.log(x))Run a function for each element.
arr.find(x => x > 2)First element matching the test, or undefined.
arr.some(x => x > 2)True if at least one element passes.
arr.every(x => x > 0)True if all elements pass the test.
arr.sort((a, b) => a - b)Sort numbers in ascending order.

Objects

const user = { name: 'Ada', age: 36 };Create an object literal.
user.nameAccess a property with dot notation.
user['age']Access a property with bracket notation.
Object.keys(user)Array of the object's own keys.
Object.values(user)Array of the object's own values.
Object.entries(user)Array of [key, value] pairs.
'name' in userTrue if the property exists on the object.
user?.address?.cityOptional chaining: safely access nested values.

Functions & Arrow Functions

function add(a, b) { return a + b; }Standard function declaration.
const add = (a, b) => a + b;Arrow function with implicit return.
const square = x => x * x;Single parameter needs no parentheses.
const greet = (name = 'world') => name;Default parameter value.
const sum = (...nums) => nums.length;Rest parameters collect args into an array.
(() => { /* ... */ })()Immediately invoked function expression (IIFE).

Conditionals & Loops

if (x > 0) { /* ... */ } else { /* ... */ }Basic if/else branching.
x > 0 ? 'pos' : 'neg'Ternary operator for inline conditions.
switch (x) { case 1: break; default: }Branch on multiple discrete values.
for (let i = 0; i < 5; i++) { }Classic counting loop.
for (const item of arr) { }Iterate over array values.
for (const key in obj) { }Iterate over an object's keys.
while (condition) { }Loop while the condition stays true.
const flag = a ?? b;Nullish coalescing: use b if a is null/undefined.

Destructuring & Spread

const [a, b] = [1, 2];Destructure values from an array.
const { name, age } = user;Destructure properties from an object.
const { id = 0 } = obj;Provide a default when the value is undefined.
const copy = [...arr];Spread to clone an array.
const merged = { ...a, ...b };Spread to merge objects (b wins on conflicts).
const [first, ...rest] = arr;Collect remaining elements with rest.

Promises & Async

fetch(url).then(res => res.json())Chain promise handlers with .then().
promise.catch(err => console.error(err))Handle a rejected promise.
async function load() { /* ... */ }Declare an async function returning a promise.
const data = await fetch(url);Pause until the promise resolves (inside async).
await Promise.all([p1, p2])Wait for all promises to resolve.
try { await fn(); } catch (e) { }Handle errors from awaited code.

Reading is good β€” doing is better. Practice JavaScript with interactive, auto-graded lessons.

Start learning JavaScript