LEARN TO CODE | QUICK REFERENCE

JAVASCRIPT CHEAT SHEET

Syntax, built-in functions and popular methods at a glance. Covers all four sections of the JavaScript course.

01 | SETUP, VARIABLES AND OUTPUT

Setup, variables and output reference
Item Use and example
Load a script Place a deferred external script in the HTML head. This is HTML, not JavaScript.

<script src="script.js" defer></script>
Console output Open the browser developer tools console to see output.

console.log("Hello!");
console.table([{ name: "Ava", score: 8 }]);
let and const Use let when reassigning. const prevents reassignment of the binding.

let score = 0;
score = score + 1;
const player = "Ava";
Comments Explain why code exists. Comments do not run.

// One-line comment
/* A comment
   across several lines */
Data types Common primitive values. Arrays and plain objects are objects.

const name = "Ava";
const age = 16;
const ready = true;
let result; // undefined
const selected = null;
console.log(typeof age); // "number"
Template literals Backticks allow interpolation and multiline strings.

const name = "Ava";
console.log(`Hello, ${name}!`);

Back to topic links

02 | NUMBERS AND CONVERSION

Numbers and conversion reference
Item Use and example
Arithmetic Use parentheses to control evaluation order.

console.log(7 + 3, 7 - 3);
console.log(7 * 3, 7 / 3);
console.log(7 % 3); // 1: remainder
console.log(2 ** 3); // 8: power
Updating values Shorthand updates the current value.

let total = 10;
total += 5;
total -= 2;
total++; // add 1
Number() Convert a complete value to a number. Invalid text becomes NaN.

console.log(Number("12.5")); // 12.5
console.log(Number("cat")); // NaN
console.log(Number("")); // 0
parseInt / parseFloat Parse a numeric prefix. These can accept trailing nonnumeric text.

console.log(parseInt("12px", 10)); // 12
console.log(parseFloat("3.5kg")); // 3.5
Number checks Check finite numbers and integers after conversion.

const value = Number("12");
console.log(Number.isFinite(value)); // true
console.log(Number.isInteger(value)); // true
Math and formatting toFixed returns text. Math.random is not for passwords or security.

console.log(Math.round(3.6)); // 4
console.log(Math.floor(3.9)); // 3
console.log(Math.ceil(3.1)); // 4
console.log(Math.abs(-5)); // 5
console.log((3.5).toFixed(2)); // "3.50"
const die = Math.floor(Math.random() * 6) + 1;

Back to topic links

03 | CONDITIONS AND LOOPS

Conditions and loops reference
Item Use and example
Comparisons Prefer strict equality: it does not convert types.

console.log(5 === "5"); // false
console.log(5 !== 4); // true
console.log(5 >= 3); // true
// Other comparisons: <, >, <=
Boolean logic && means AND, || means OR, ! means NOT.

const age = 16;
const member = true;
console.log(age >= 12 && member); // true
console.log(age < 12 || member); // true
console.log(!member); // false
if / else if / else Only the first matching branch runs.

const score = 7;
if (score >= 8) {
  console.log("Excellent");
} else if (score >= 5) {
  console.log("Passed");
} else {
  console.log("Keep practising");
}
for Repeat with a counter. The loop body is the code inside the braces.

for (let i = 0; i < 3; i++) {
  console.log(i); // 0, then 1, then 2
}
for...of Read each value in an iterable such as an array.

for (const name of ["Ava", "Sam"]) {
  console.log(name);
}
while Check the condition before every repetition.

let count = 0;
while (count < 3) {
  count++;
}
console.log(count); // 3
break and continue break exits the loop; continue skips to its next iteration.

for (let n = 0; n < 10; n++) {
  if (n === 2) continue;
  if (n === 4) break;
  console.log(n); // 0, 1, 3
}

Back to topic links

04 | STRING METHODS

String methods reference
Item Use and example
length and indexing Indexes start at 0. length is a property, not a method.

const word = "Hello";
console.log(word.length); // 5
console.log(word[0]); // "H"
slice(start, end) The end index is excluded; negative indexes count from the end.

const word = "Computer";
console.log(word.slice(0, 4)); // "Comp"
console.log(word.slice(-3)); // "ter"
Case and whitespace Strings are immutable. Store the returned string.

const name = "  Ava  ";
console.log(name.trim().toLowerCase()); // "ava"
console.log(name.trim().toUpperCase()); // "AVA"
Searching Searches are case-sensitive. indexOf returns -1 if missing.

const text = "Learn JavaScript";
console.log(text.includes("Java")); // true
console.log(text.startsWith("Learn")); // true
console.log(text.endsWith("Script")); // true
console.log(text.indexOf("Java")); // 6
Replacing replace changes the first string match; replaceAll changes all.

console.log("a-a".replace("a", "b")); // "b-a"
console.log("a-a".replaceAll("a", "b")); // "b-b"
split and join split makes an array; join combines array values into a string.

const names = "Ava,Sam".split(",");
console.log(names.join(" / ")); // "Ava / Sam"

Back to topic links

05 | FUNCTIONS AND SCOPE

Functions and scope reference
Item Use and example
Declaration and return Parameters receive inputs. return sends a result to the caller.

function add(a, b) {
  return a + b;
}
const total = add(3, 4); // 7
Default parameter The default is used for missing or undefined arguments.

function greet(name = "visitor") {
  return `Hello, ${name}`;
}
console.log(greet());
Arrow function A single expression can return implicitly.

const double = (number) => number * 2;
console.log(double(4)); // 8
Block scope let and const are limited to their enclosing block.

let score = 0;
if (true) {
  const bonus = 5;
  score += bonus;
}
// bonus is unavailable here
Debugging Use breakpoints in browser developer tools to pause and inspect values.

const score = 5;
console.log("Before update:", score);
console.assert(score >= 0, "Negative score");

Back to topic links

06 | ARRAY BASICS

Array basics reference
Item Use and example
Create and access Arrays use zero-based indexes and can grow.

const scores = [8, 5, 9];
console.log(scores[0]); // 8
scores[1] = 7;
console.log(scores.length); // 3
push and pop Both mutate the array. push returns its new length; pop returns the removed item.

const names = ["Ava"];
names.push("Sam");
const last = names.pop(); // "Sam"
unshift and shift Add or remove at the start. Both mutate the array.

const names = ["Ava"];
names.unshift("Sam");
const first = names.shift(); // "Sam"
slice and splice slice copies a range; splice removes or inserts in the original array.

const items = ["A", "B", "C"];
const copy = items.slice(0, 2); // ["A", "B"]
items.splice(1, 1, "X"); // ["A", "X", "C"]
includes and indexOf Check for a primitive value or find its first position.

const names = ["Ava", "Sam"];
console.log(names.includes("Sam")); // true
console.log(names.indexOf("Lee")); // -1
Copy and spread Spread makes a shallow copy. Nested objects remain shared.

const original = [1, 2];
const copy = [...original, 3];
console.log(copy); // [1, 2, 3]

Back to topic links

07 | ARRAY TRANSFORMATIONS

Array transformations reference
Item Use and example
map Return a new array containing each transformed value.

const doubled = [1, 2, 3].map((n) => n * 2);
// [2, 4, 6]
filter Return a new array containing values that pass the test.

const passed = [3, 8, 5].filter((n) => n >= 5);
// [8, 5]
find and findIndex Return the first matching value or index. Missing: undefined or -1.

const scores = [3, 8, 5];
const first = scores.find((n) => n >= 5); // 8
const index = scores.findIndex((n) => n >= 5); // 1
some and every Test whether at least one value, or every value, matches.

console.log([3, 8].some((n) => n > 5)); // true
console.log([3, 8].every((n) => n > 5)); // false
reduce Combine values into one result. Supply an initial accumulator.

const total = [8, 5, 9].reduce(
  (sum, score) => sum + score,
  0
); // 22
sort sort mutates. Supply a comparator for numeric order.

const scores = [10, 2, 8];
const ordered = [...scores].sort((a, b) => a - b);
// [2, 8, 10]; scores is unchanged
forEach Run an action for each item. It returns undefined, not a new array.

["Ava", "Sam"].forEach((name, index) => {
  console.log(index, name);
});

Back to topic links

08 | OBJECTS AND PROPERTIES

Objects and properties reference
Item Use and example
Create, read and update Use dot notation or brackets for a computed property name.

const player = { name: "Ava", score: 8 };
player.score += 1;
const key = "name";
console.log(player[key]); // "Ava"
Object methods An object can store functions as methods.

const player = {
  name: "Ava",
  greet() {
    return `Hi, ${this.name}`;
  }
};
console.log(player.greet());
keys, values and entries Inspect an object or loop through its own enumerable properties.

const player = { name: "Ava", score: 8 };
console.log(Object.keys(player));
console.log(Object.values(player));
for (const [key, value] of Object.entries(player)) {
  console.log(key, value);
}
Destructuring and spread Extract values and make a shallow copy with an updated property.

const player = { name: "Ava", score: 8 };
const { name, score } = player;
const updated = { ...player, score: 10 };
Optional chaining and defaults ?. stops at null or undefined; ?? supplies a default for those values.

const user = {};
const city = user.address?.city ?? "Unknown";
console.log(city);

Back to topic links

09 | SELECT AND CHANGE THE DOM

Select and change the dom reference
Item Use and example
Select elements Examples in this group require matching HTML elements. Check a single match for null.

const title = document.querySelector("#title");
if (title) {
  title.textContent = "Hello!";
}
Select many querySelectorAll returns a static NodeList.

document.querySelectorAll(".card").forEach((card) => {
  card.classList.add("ready");
});
textContent Display text, including user input, without interpreting it as HTML.

const message = document.querySelector("#message");
if (message) {
  message.textContent = "<strong>Hello</strong>";
}
classList Use CSS classes for appearance and state.

const box = document.querySelector("#box");
if (box) {
  box.classList.add("active");
  box.classList.remove("hidden");
  box.classList.toggle("selected");
  console.log(box.classList.contains("active"));
}
Attributes and properties Use properties for current input values and boolean state.

const button = document.querySelector("#save");
if (button) {
  button.disabled = true;
  button.setAttribute("aria-label", "Save changes");
}
Create, append and remove Create nodes and set text instead of building HTML from user input.

const list = document.querySelector("#list");
if (list) {
  const item = document.createElement("li");
  item.textContent = "New task";
  list.append(item);
  // item.remove();
}

Back to topic links

10 | EVENTS

Events reference
Item Use and example
addEventListener Assumes a button with id start. Pass a function, not its result.

const button = document.querySelector("#start");
if (button) {
  button.addEventListener("click", () => {
    console.log("Started");
  });
}
Event object currentTarget is the element with the listener. target is where the event began.

const button = document.querySelector("#start");
if (button) {
  button.addEventListener("click", (event) => {
    console.log(event.currentTarget.id);
  });
}
input and change input reacts while editing. change reacts when a change is committed.

const field = document.querySelector("#name");
if (field) {
  field.addEventListener("input", (event) => {
    console.log(event.target.value);
  });
}
Keyboard events Check event.key for the key name.

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape") {
    console.log("Close the panel");
  }
});

Back to topic links

11 | FORMS AND VALIDATION

Forms and validation reference
Item Use and example
Read form controls Assumes text input #name and checkbox #agree. value is text; checked is boolean.

const name = document.querySelector("#name");
const agree = document.querySelector("#agree");
if (name && agree) {
  console.log(name.value.trim(), agree.checked);
}
Handle submit Assumes form #entry and input #name. Prevent the normal page submission.

const form = document.querySelector("#entry");
const name = document.querySelector("#name");
if (form && name) {
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    if (!form.reportValidity()) return;
    console.log(name.value.trim());
  });
}
Validate a number Reject blank input before Number(), because Number("") is 0.

const raw = "12";
const age = Number(raw);
const valid = raw.trim() !== ""
  && Number.isInteger(age)
  && age >= 0;
console.log(valid);
FormData Assumes form #entry. Controls need name attributes to appear in FormData.

const form = document.querySelector("#entry");
if (form) {
  const data = new FormData(form);
  console.log(data.get("name"));
}

Use HTML required, type, min, max and minlength where appropriate. Browser validation helps users; a server must validate submitted data independently.

Back to topic links

12 | JSON AND BROWSER STORAGE

Json and browser storage reference
Item Use and example
JSON.stringify and JSON.parse Convert supported data to JSON text and back. Invalid JSON throws.

const text = JSON.stringify({ name: "Ava", score: 8 });
const player = JSON.parse(text);
console.log(player.name);
localStorage Stores strings for this origin across visits, subject to browser settings.

try {
  localStorage.setItem("cafe:theme", "dark");
  const theme = localStorage.getItem("cafe:theme");
  localStorage.removeItem("cafe:theme");
} catch (error) {
  console.error("Storage unavailable:", error);
}
Store an array Check parsed data before using it. Missing keys return null.

let tasks = [];
try {
  const raw = localStorage.getItem("cafe:tasks");
  const saved = raw === null ? [] : JSON.parse(raw);
  if (Array.isArray(saved)) tasks = saved;
  localStorage.setItem("cafe:tasks", JSON.stringify(tasks));
} catch (error) {
  console.error("Could not load or save tasks:", error);
}
sessionStorage Similar API, scoped to the page session in a tab. It is not a server login session.

try {
  sessionStorage.setItem("cafe:draft", "Hello");
  console.log(sessionStorage.getItem("cafe:draft"));
} catch (error) {
  console.error("Draft storage unavailable:", error);
}

Do not store passwords or secrets in browser storage. JSON does not preserve methods, undefined values or all JavaScript types. Validate the shape and values of restored records, not only whether they form an array.

Back to topic links

13 | PROMISES, ASYNC AND AWAIT

Promises, async and await reference
Item Use and example
Promise Represents an eventual result or failure. then handles success; catch handles failure.

Promise.resolve("Ready")
  .then((message) => console.log(message))
  .catch((error) => console.error(error));
async / await async functions return promises. await pauses that function until settlement.

async function loadMessage() {
  const message = await Promise.resolve("Ready");
  return message;
}
loadMessage().then(console.log);
try / catch / finally Handle failure and run cleanup whether the operation succeeds or fails.

async function run() {
  try {
    const result = await Promise.resolve(42);
    console.log(result);
  } catch (error) {
    console.error(error);
  } finally {
    console.log("Finished");
  }
}
run();
Promise.all Wait for all results. Rejects if one input promise rejects.

async function loadBoth() {
  const results = await Promise.all([
    Promise.resolve("A"),
    Promise.resolve("B")
  ]);
  console.log(results);
}
loadBoth();
Timers A timeout schedules a callback after at least the requested delay.

const timer = setTimeout(() => {
  console.log("Later");
}, 1000);
clearTimeout(timer); // cancel it

Back to topic links

14 | FETCH AND ERROR HANDLING

Fetch and error handling reference
Item Use and example
GET JSON Example expects /data.json on a local HTTP server. fetch does not reject just because of a 404.

async function loadData() {
  try {
    const response = await fetch("/data.json");
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Loading failed:", error);
  }
}
loadData();
POST JSON Example requires an API route that accepts JSON at /api/items.

async function saveItem() {
  const response = await fetch("/api/items", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Revise" })
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
}
saveItem().catch(console.error);
Cancel a request AbortController can cancel an in-progress fetch.

const controller = new AbortController();
fetch("/data.json", { signal: controller.signal })
  .catch((error) => {
    if (error.name !== "AbortError") console.error(error);
  });
controller.abort();

Use a local HTTP server, such as the VS Code Live Server extension, for fetch examples. Cross-origin APIs need suitable server CORS headers. mode: "no-cors" does not make a JSON response readable. Keep private API keys on a server.

Back to topic links

15 | QUIZ PROJECT PATTERNS

Quiz project patterns reference
Item Use and example
Question data Store the correct option index alongside each question.

const questions = [{
  prompt: "Which keyword declares a constant?",
  options: ["let", "const", "while"],
  answer: 1
}];
Read one answer Use radio inputs sharing name="answer", with values 0, 1, 2, and so on.

const selected = document.querySelector(
  'input[name="answer"]:checked'
);
if (selected) {
  const optionIndex = Number(selected.value);
  console.log(optionIndex);
}
Score once The Set prevents the same question being scored repeatedly.

let score = 0;
const answered = new Set();
function checkAnswer(index, chosen, correct) {
  if (answered.has(index)) return;
  answered.add(index);
  if (chosen === correct) score++;
}
checkAnswer(0, 1, 1);
checkAnswer(0, 1, 1);
console.log(score); // 1

Back to topic links

16 | TO-DO PROJECT PATTERNS

To-do project patterns reference
Item Use and example
Stable IDs A stable identifier remains useful when array positions change.

const tasks = [
  { id: "task-1", title: "Revise", done: false },
  { id: "task-2", title: "Practise", done: true }
];
const remaining = tasks.filter((task) => !task.done);
Update and delete Return new arrays. Identify the task by ID rather than display text.

let tasks = [{ id: "task-1", title: "Revise", done: false }];
tasks = tasks.map((task) =>
  task.id === "task-1" ? { ...task, done: true } : task
);
tasks = tasks.filter((task) => task.id !== "task-1");
Render a list Assumes ul #tasks. Rebuild it from application state.

const tasks = [{ title: "Revise", done: false }];
const list = document.querySelector("#tasks");
if (list) {
  list.replaceChildren();
  for (const task of tasks) {
    const item = document.createElement("li");
    item.textContent = task.title;
    item.classList.toggle("done", task.done);
    list.append(item);
  }
}

Back to topic links

COMMON MIX-UPS

  • = assigns; === compares values without type conversion.
  • String and array indexes begin at 0; slice excludes its end index.
  • const prevents reassignment; its objects and arrays can still change.
  • return sends a result back; console.log displays it.
  • map returns an array; forEach returns undefined.
  • sort mutates and needs a comparator to sort numbers numerically.
  • Input values are strings. Check blanks before converting to numbers.
  • Use textContent when displaying user text.
  • fetch needs an explicit response.ok check for HTTP errors.
  • Browser storage is not a database or a secure login system.

BACK TO JAVASCRIPT

MDN references: