Cheat sheet · Languages
JavaScript cheat sheet
Variables, strings, arrays, objects, functions and async code in modern JavaScript.
- Sections
- 6
- Items
- 43
- Area
- Languages
- Download
- PNG, PDF
Cheat sheet
JavaScript
Variables, strings, arrays, objects, functions and async code in modern JavaScript.
Variables and types
const x = 1- A value that is not reassigned (use by default)
let y = 2- A value that changes later
typeof value- "number", "string", "boolean", "undefined", "object", "function"
null / undefined- Nothing on purpose / nothing set yet
a === b- Equal in value and type (avoid ==)
a ?? b- Use b only when a is null or undefined
obj?.name- Read name only if obj exists
Strings
`Hi ${name}`- Template string with a value inside
s.length- Number of characters
s.slice(1, 4)- Characters from index 1 up to 3
s.split(",") / arr.join(",")- Text to array / array to text
s.includes("a")- Does it contain this text?
s.replace("a", "b")- Replace the first match (replaceAll for all)
s.trim() s.toUpperCase()- Remove edge spaces / change case
Arrays
arr.push(x) / arr.pop()- Add / remove at the end
arr.unshift(x) / arr.shift()- Add / remove at the start
arr.map(fn)- New array with fn applied to each item
arr.filter(fn)- New array with items where fn is true
arr.reduce((acc, x) => acc + x, 0)- Combine all items into one value
arr.find(fn) / arr.findIndex(fn)- First matching item / its position
arr.some(fn) / arr.every(fn)- Any item matches? / all items match?
arr.includes(x)- Is the value in the array?
arr.slice(1, 3) / arr.splice(1, 2)- Copy a part / remove items in place
arr.sort((a, b) => a - b)- Sort numbers (changes the array)
[...a, ...b]- Join arrays into a new one
Objects
const { a, b } = obj- Take properties into variables
{ ...obj, a: 1 }- Copy an object and change a property
Object.keys(obj)- Array of property names
Object.values(obj)- Array of values
Object.entries(obj)- Array of [name, value] pairs
JSON.stringify(obj) / JSON.parse(text)- Object to text / text to object
Functions and loops
const add = (a, b) => a + b- Arrow function
function f(a, b = 2) { }- Default value for a parameter
function f(...args) { }- Collect extra arguments in an array
for (const x of arr) { }- Loop over the values
for (const k in obj) { }- Loop over the property names
arr.forEach(fn)- Run fn for each item (no result)
Async code
const res = await fetch(url)- Wait for a web request
const data = await res.json()- Read the body as JSON
async function f() { }- A function that can use await
try { } catch (err) { }- Handle a failure
await Promise.all([p1, p2])- Wait for several at once
setTimeout(fn, 1000)- Run fn after one second
Remember
- These make a new array and leave the old one alone: map, filter, slice. These change the old one: push, pop, splice, sort.
- Falsy values: false, 0, "", null, undefined, NaN. Everything else counts as true in an if.
Learn it properly
A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.