JavaScript Cheat Sheet
7 groups · 23 topics · Updated
In the examples, // → shows the result of that line.
Basics
The building blocks every program uses.
Variables
const city = "Pune"; // cannot be replaced
let score = 10; // can be replaced
score = score + 5; // → 15- Use
constby default,letwhen the value changes. varis the old way. Avoid it.
Data types
| Value | Type |
|---|---|
"hello" |
string (text) |
42, 3.14 |
number |
true, false |
boolean |
undefined |
no value set yet |
null |
empty on purpose |
{ a: 1 } |
object |
[1, 2, 3] |
array (a kind of object) |
typeof "hi"; // → "string"
typeof 42; // → "number"
typeof null; // → "object" (old bug)
typeof []; // → "object"
Array.isArray([]); // → trueOperators
7 + 3; // → 10
7 % 3; // → 1 (remainder)
2 ** 3; // → 8 (power)
5 === "5"; // → false (strict: use this)
5 == "5"; // → true (loose: avoid)
5 !== 3; // → true
true && false; // → false (and)
true || false; // → true (or)
!true; // → false (not)Shortcuts
const age = 20;
age >= 18 ? "adult" : "child"; // → "adult"
null ?? "none"; // → "none"
0 ?? "none"; // → 0
0 || "none"; // → "none"
const user = { profile: null };
user.profile?.city; // → undefineda ? b : cmeans "if a, then b, else c".??falls back only fornullorundefined.||falls back for any falsy value.?.stops safely instead of throwing an error.
Truthy and falsy
Falsy: false, 0, "", null, undefined, NaN. Everything else is truthy.
Boolean(""); // → false
Boolean("0"); // → true
Boolean([]); // → true
Boolean({}); // → true
!!0; // → falseStrings and numbers
Working with text and maths.
Strings
const s = "hello";
`Hi ${s}!`; // → "Hi hello!"
s.length; // → 5
s[0]; // → "h"
s.at(-1); // → "o"
s.toUpperCase(); // → "HELLO"
s.includes("ell"); // → true
s.startsWith("he"); // → true
s.indexOf("l"); // → 2
s.slice(1, 3); // → "el"
s.replace("l", "L"); // → "heLlo"
s.replaceAll("l", "L"); // → "heLLo"
"a,b".split(","); // → ["a", "b"]
" hi ".trim(); // → "hi"
"ab".repeat(2); // → "abab"
"5".padStart(3, "0"); // → "005"Strings never change. Every method returns a new string.
Numbers
Number("42"); // → 42
parseInt("42px"); // → 42
parseFloat("3.5kg"); // → 3.5
String(42); // → "42"
(3.14159).toFixed(2); // → "3.14"
Math.round(4.5); // → 5
Math.floor(4.9); // → 4
Math.ceil(4.1); // → 5
Math.max(1, 5, 3); // → 5
Math.min(1, 5, 3); // → 1
Math.abs(-7); // → 7
0.1 + 0.2 === 0.3; // → false
Number.isNaN(NaN); // → true
// random whole number from 1 to 6
Math.floor(Math.random() * 6) + 1;Logic and loops
Making decisions and repeating work.
If and switch
const marks = 72;
let grade;
if (marks >= 80) {
grade = "A";
} else if (marks >= 60) {
grade = "B";
} else {
grade = "C";
}
grade; // → "B"
switch (grade) {
case "A":
case "B":
grade = "pass";
break; // stop here
default:
grade = "retry";
}
grade; // → "pass"Loops
const list = ["a", "b", "c"];
for (const item of list) {} // each value
for (let i = 0; i < 3; i++) {} // by index
for (const key in { x: 1 }) {} // object keys
list.forEach((item, i) => {}); // as a method
let n = 3;
while (n > 0) n--; // repeat until false
n; // → 0breakleaves the loop.continueskips to the next round.
Errors
let msg;
try {
throw new Error("Something broke");
} catch (error) {
msg = error.message; // runs on error
} finally {
// always runs
}
msg; // → "Something broke"Functions and classes
Packaging code so you can reuse it.
Functions
function add(a, b) {
return a + b;
}
add(2, 3); // → 5
// arrow function: the same, shorter
const double = (x) => x * 2;
double(4); // → 8
// default value
const greet = (who = "you") => `Hi ${who}`;
greet(); // → "Hi you"
// any number of inputs
const total = (...nums) =>
nums.reduce((sum, x) => sum + x, 0);
total(1, 2, 3); // → 6- No braces: the value is returned automatically.
- With
{ }you must writereturn.
Classes
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
new Dog("Rex").speak(); // → "Rex barks"Modules
// maths.js
export const PI = 3.14;
export default function square(x) {
return x * x;
}
// app.js
import square, { PI } from "./maths.js";Arrays and objects
Storing and reshaping collections of data.
Arrays: change the list
const a = [1, 2, 3];
a[0]; // → 1
a.at(-1); // → 3
a.length; // → 3
a.push(4); // add to the end
a.pop(); // → 4 (remove from end)
a.unshift(0); // add to the start
a.shift(); // → 0 (remove from start)
a.splice(1, 1); // → [2] (remove at index 1)
a; // → [1, 3]
a.reverse(); // → [3, 1]sort() sorts as text unless you say how to compare:
[10, 9].sort(); // → [10, 9]
[10, 9].sort((a, b) => a - b); // → [9, 10]Arrays: make something new
These leave the original untouched.
const n = [1, 2, 3];
n.map((x) => x * 2); // → [2, 4, 6]
n.filter((x) => x > 1); // → [2, 3]
n.reduce((t, x) => t + x, 0); // → 6
n.find((x) => x > 1); // → 2
n.findIndex((x) => x > 1); // → 1
n.includes(2); // → true
n.indexOf(3); // → 2
n.some((x) => x > 2); // → true
n.every((x) => x > 2); // → false
n.slice(1); // → [2, 3]
[1].concat([2]); // → [1, 2]
n.join("-"); // → "1-2-3"
[[1], [2]].flat(); // → [1, 2]
[3, 1, 2].toSorted(); // → [1, 2, 3]map changes each item, filter keeps some, reduce combines all.
Objects
const user = { name: "Asha", age: 28 };
user.name; // → "Asha"
user["age"]; // → 28
user.city = "Pune"; // add or change
delete user.age; // remove
"name" in user; // → true
Object.keys(user); // → ["name", "city"]
Object.values(user); // → ["Asha", "Pune"]
// a method is a function in an object
const counter = {
count: 0,
add() {
return ++this.count;
},
};
counter.add(); // → 1Destructuring and spread
const [x, y] = [10, 20];
y; // → 20
const book = { title: "Dune" };
const { title, year = 2026 } = book;
title; // → "Dune"
year; // → 2026 (the default)
const more = [...[1, 2], 3]; // → [1, 2, 3]
const p = { name: "Asha", age: 28 };
const older = { ...p, age: 29 };
older.age; // → 29
p.age; // → 28 (original unchanged)Map and Set
const seen = new Set([1, 2, 2, 3]);
seen.size; // → 3 (no duplicates)
seen.has(2); // → true
seen.add(4);
seen.delete(1);
[...new Set([1, 1, 2])]; // → [1, 2]
const ages = new Map();
ages.set("Asha", 28);
ages.get("Asha"); // → 28
ages.has("Ravi"); // → false
ages.size; // → 1Browser and async
Talking to the page, the user and the server.
Async code
// async / await: wait for slow work
async function loadUser() {
try {
const res = await fetch("/api/user");
if (!res.ok) throw new Error(res.status);
return await res.json();
} catch (error) {
console.error(error);
}
}
// the older .then() style
fetch("/api/user")
.then((res) => res.json())
.then((user) => console.log(user))
.catch((error) => console.error(error));
// run several at the same time
await Promise.all([loadA(), loadB()]);
setTimeout(() => {}, 1000); // once
setInterval(() => {}, 1000); // repeatsForget await and you get a promise, not the value.
The DOM
// find
document.querySelector("h1"); // first
document.querySelectorAll(".item"); // all
// change
el.textContent = "New text";
el.classList.add("active");
el.classList.toggle("hidden");
el.style.color = "green";
el.setAttribute("id", "title");
// create and remove
const li = document.createElement("li");
list.append(li);
li.remove();Events
button.addEventListener("click", (e) => {
e.target; // the element that was clicked
});
form.addEventListener("submit", (e) => {
e.preventDefault(); // no page reload
});Common events: click, input, change, submit, keydown, scroll.
JSON and storage
JSON.stringify({ a: 1 }); // → '{"a":1}'
JSON.parse('{"a":1}').a; // → 1localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");Watch out
The slips that catch everyone.
Common mistakes
| Mistake | Fix |
|---|---|
= inside a condition |
Compare with === |
Using == |
Use === |
No return inside { } |
Add return |
Missing await |
Add it, or you get a promise |
[1] === [1] is false |
Compare the values inside |
A const object still changes |
const only blocks reassignment |
.sort() on numbers |
Pass (a, b) => a - b |