iZONE

JavaScript Cheatsheet

A practical guide to JavaScript essentials: arrays, async/await, DOM, and modules.

Resources

Basics: Variables & Scope

Variables are how your program remembers things. `const` locks the value in, `let` keeps it flexible — and scope controls where each one can actually be used.

const / let / var

JavaScript

// cannot change
const birthYear = 2000;

// can change
let currentAge = 25;

// reassign let ✅
currentAge = 26;

// reassign const ❌
birthYear = 1995; // TypeError

Start with `const` for everything. Only switch to `let` if you actually need to change the value later.

naming variables

JavaScript

// ✅ good names
const userName = "Alice";
const itemCount = 5;
const isLoggedIn = true;

// fixed constant ✅
const MAX_SIZE = 100;

// ❌ avoid
const x = "Alice";
// unclear name

const myvar = 5;
// no camelCase

const logged = true;
// ambiguous

Name it after what it holds — `userAge` is clearer than `x` or `data`.

block scope

JavaScript

if (true) {
  const msg = "inside";
  // ✅ works here
  console.log(msg);
}

// ❌ ReferenceError
// msg doesn't exist out here
console.log(msg);

`var` ignores block scope and leaks out. Another reason to avoid it.

const with objects & arrays

JavaScript

const user = { name: "Alice" };

// reassign const ❌
// user = { name: "Bob" }; // TypeError

// change contents ✅
user.name = "Bob";

// same with arrays
const nums = [1, 2, 3];

// add item ✅
nums.push(4);

// reassign ❌
// nums = [5, 6]; // TypeError

Think of `const` as locking the box — not what's inside it.

destructuring

JavaScript

// from an array
const colors = ["red", "green", "blue"];
const [first, second] = colors;
// first = "red"
// second = "green"

// from an object
const user = { 
  name: "Alice", 
  age: 30 
};
const { name, age } = user;
// name = "Alice"
// age = 30

// with a default value
const { role = "viewer" } = user;
// role = "viewer" ⤵
// field didn't exist, fallback used

Destructuring just saves you from writing `user.name`, `user.age` over and over.

Basics: Data Types

Every value in JavaScript has a type — and some of them behave in ways you won't expect. Getting comfortable with null, undefined, and how comparisons work will save you a lot of head-scratching later.

the five primitives

JavaScript

const name    = "Alice"; // string
const age     = 30;      // number
const isOn    = true;    // boolean
const empty   = null;    // null
const notSet  = undefined; // undefined

typeof

JavaScript

typeof "hello"   // "string"
typeof 42        // "number"
typeof true      // "boolean"
typeof undefined // "undefined"

// ⚠️ known JS bug
typeof null      // "object"
// null is NOT an object

// ✅ check for null properly
value === null

`typeof null` returns `'object'` — it's a JS bug. Always use `value === null` to check for null.

=== vs ==

JavaScript

// == converts types ⚠️
0  == false  // true
"" == false  // true
null == undefined // true

// === never converts ✅
0   === false // false
""  === false // false
null === undefined // false

Always use `===`. The `==` operator converts types silently and causes hard-to-find bugs.

truthy & falsy

JavaScript

// falsy — act as false
if (0)         // skipped
if ("")        // skipped
if (null)      // skipped
if (undefined) // skipped
if (NaN)       // skipped

// truthy — act as true
if (1)         // runs
if ("hello")   // runs
if ([])        // runs ← empty array!
if ({})        // runs ← empty object!

Empty array `[]` and empty object `{}` are truthy — this surprises a lot of beginners.

type conversion

JavaScript

// to number
Number("42")     // 42
Number("abc")    // NaN — failed
parseInt("42px") // 42 — stops at first non-digit

// to string
String(42)       // "42"
String(true)     // "true"
String(null)     // "null"

// decimal formatting
// ⚠️ returns a STRING
(3.14159).toFixed(2) // "3.14"

// ✅ wrap if you need a number
Number((3.14159).toFixed(2)) // 3.14

`toFixed()` returns a string, not a number. Wrap with `Number()` if you need to do math after.

Strings

Strings are just text. But there's quite a bit you can do with them — search inside, cut pieces out, swap words, change case. And one thing worth knowing upfront: string methods don't touch the original, they always hand back a new string.

template literals

JavaScript

const name = "Alice";
const age  = 30;

// old way ❌
const msg1 = "Hi " + name + ", age " + age;

// template literal ✅
const msg2 = `Hi ${name}, age ${age}`;

// any expression works
const result = `2 + 2 = ${2 + 2}`;
// "2 + 2 = 4"

// multi-line — no \n needed
const poem = `
  Roses are red,
  Violets are blue.
`;

Use template literals instead of joining strings with `+` — much cleaner to read.

searching a string

JavaScript

const str = "Hello, World!";

// yes/no checks
str.includes("World")   // true
str.startsWith("Hello") // true
str.endsWith("!")       // true

// find position
str.indexOf("o")
// 4 — first match

str.indexOf("xyz")
// -1 — not found

transforming a string

JavaScript

"hello".toUpperCase()
// "HELLO"

"HELLO".toLowerCase()
// "hello"

"  hello  ".trim()
// "hello" — removes both ends

"ha".repeat(3)
// "hahaha"

// removes left side only
"  hello  ".trimStart()
// "hello  "

// pad with zeros — useful for formatting
"5".padStart(3, "0")
// "005"

String methods never change the original — they always return a new string.

slice, split & replace

JavaScript

const text = "Hello, World!";

// slice — cut by position
text.slice(0, 5)
// "Hello"

text.slice(-6)
// "orld!" — last 6 chars

// split — break into array
text.split(", ")
// ["Hello", "World!"]

// replace
text.replace("World", "JS")
// "Hello, JS!" — first match

text.replaceAll("l", "L")
// "HeLLo, WorLd!" — all matches

Numbers & Math

JavaScript uses one number type for everything — whole, decimal, all of it. And there's a built-in Math object that handles rounding, random numbers, and a bunch of other useful stuff.

special number values

JavaScript

10 / 0    // Infinity
-10 / 0   // -Infinity
"abc" * 2 // NaN

// check NaN ❌
NaN === NaN
// false — never works

// unreliable ⚠️
isNaN("hello")
// true — converts first

// correct way ✅
Number.isNaN(NaN)     // true
Number.isNaN("hello") // false

Never check NaN with `===` — NaN is the only value not equal to itself. Always use `Number.isNaN()`.

formatting numbers

JavaScript

// decimal places
// ⚠️ returns a STRING
(3.14159).toFixed(2)
// "3.14"

// add commas for readability
(1234567).toLocaleString()
// "1,234,567"

// convert to other bases
(255).toString(16) // "ff"  — hex
(255).toString(2)  // "11111111" — binary

`toFixed()` returns a string, not a number. Wrap with `Number()` if you need to do math after.

Math — rounding, min, max & random

JavaScript

Math.round(4.5) // 5 — nearest whole
Math.floor(4.9) // 4 — always down
Math.ceil(4.1)  // 5 — always up
Math.abs(-5)    // 5 — remove minus
Math.max(1,5,3) // 5 — largest
Math.min(1,5,3) // 1 — smallest
Math.sqrt(16)   // 4 — square root
Math.pow(2, 10) // 1024

// random decimal 0–1
Math.random()
// e.g. 0.742

// random whole number 1–10
const rand = Math.floor(Math.random() * 10) + 1;

// random between any range
function randomInt(min, max) {
  return Math.floor(
    Math.random() * (max - min + 1)
  ) + min;
}
// dice roll
randomInt(1, 6);

Arrays

An array is just an ordered list of values. And honestly, a lot of JavaScript work comes down to looping through arrays, picking items out, and reshaping the data. These methods will come up constantly.

create and access items

JavaScript

const fruits = ["apple", "banana", "cherry"];

fruits[0]     // "apple" — first item
fruits[2]     // "cherry" — third item

// last item
fruits.at(-1)
// "cherry"

fruits.length // 3

add and remove items

JavaScript

const arr = [1, 2, 3];

// add to end ✅
arr.push(4)
// [1, 2, 3, 4]

// remove from end
arr.pop()
// returns 4 → [1, 2, 3]

// add to start
arr.unshift(0)
// [0, 1, 2, 3]

// remove from start
arr.shift()
// returns 0 → [1, 2, 3]

map — transform every item

JavaScript

const numbers = [1, 2, 3, 4, 5];

// double every number
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// pull names from objects
const users = [
  { name: "Alice" },
  { name: "Bob" }
];
const names = users.map(u => u.name);
// ["Alice", "Bob"]

filter — keep matching items

JavaScript

const numbers = [1, 2, 3, 4, 5, 6];

// keep even numbers only
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]

// keep active users only
const users = [
  { name: "Alice", active: true  },
  { name: "Bob",   active: false },
];
const active = users.filter(u => u.active);
// [{ name: "Alice", active: true }]

reduce — collapse into one value

JavaScript

const numbers = [1, 2, 3, 4, 5];

// add all numbers
const total = numbers.reduce(
  (acc, n) => acc + n, 0
);
// acc starts at 0 → 15

// find the largest
const max = numbers.reduce(
  (biggest, n) => n > biggest ? n : biggest, 0
);
// 5

find & search

JavaScript

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob"   },
];

// first match
users.find(u => u.id === 1)
// { id: 1, name: "Alice" }

// index of match
users.findIndex(u => u.id === 2)
// 1 — returns -1 if not found

// at least one matches?
users.some(u => u.name === "Bob")
// true

// all match?
users.every(u => u.id > 0)
// true

// contains value?
[1, 2, 3].includes(2)
// true

other useful methods

JavaScript

// combine into string
[1, 2, 3].join(" - ")
// "1 - 2 - 3"

// copy a section
[1, 2, 3].slice(1, 3)
// [2, 3]

// combine two arrays
[1, 2].concat([3, 4])
// [1, 2, 3, 4]

// sort numbers correctly ✅
[10, 2, 30].sort((a, b) => a - b)
// [2, 10, 30]

// flatten nested arrays
[1, [2, 3], [4, 5]].flat()
// [1, 2, 3, 4, 5]

// remove duplicates
const nums = [1, 2, 2, 3, 3];
const unique = [...new Set(nums)];
// [1, 2, 3]

`sort()` treats items as text by default. Always pass a compare function when sorting numbers.

Objects

An object groups related data together under named keys. Think of it like a labelled form — each field has a name and a value.

create and access an object

JavaScript

const user = {
  name:  "Alice",
  age:   30,
  email: "[email protected]",
};

// dot notation
user.name
// "Alice"

// bracket notation
user["age"]
// 30

// add a field
user.city = "London";

// delete a field
delete user.email;

methods — functions inside objects

JavaScript

const person = {
  name: "Alice",
  age:  30,

  greet() {
    return `Hi, I'm ${this.name}, age ${this.age}.`;
    // 'this' = the person object
  },
};

person.greet();
// "Hi, I'm Alice, age 30."

loop over keys and values

JavaScript

const scores = { Alice: 95, Bob: 87, Carol: 91 };

Object.keys(scores)
// ["Alice", "Bob", "Carol"]

Object.values(scores)
// [95, 87, 91]

Object.entries(scores)
// [["Alice",95], ["Bob",87], ["Carol",91]]

// loop over key-value pairs
for (const [name, score] of Object.entries(scores)) {
  console.log(`${name}: ${score}`);
}

copy and merge objects

JavaScript

const original = { name: "Alice", age: 30 };

// shallow copy
const copy = { ...original };

// merge — right side wins on matching keys
const extra  = { city: "London", age: 31 };
const merged = { ...original, ...extra };
// { name: "Alice", age: 31, city: "London" }

Spread makes a shallow copy — nested objects are still shared. Use `structuredClone()` for a full deep copy.

Functions

A function is a reusable block of code. Write it once, call it as many times as you need — and pass in different values each time.

three ways to write a function

JavaScript

// declaration — hoisted
function add(a, b) {
  return a + b;
}

// expression — stored in variable
const multiply = function(a, b) {
  return a * b;
};

// arrow — shortest, most common
const square = n => n * n;
const greet  = name => `Hi ${name}!`;
const sum    = (a, b) => a + b;

Use arrow functions by default. They're shorter and work great for callbacks.

default parameters

JavaScript

// greeting defaults to "Hello" if not passed
function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

greet("Alice");
// "Hello, Alice!"

greet("Alice", "Hi");
// "Hi, Alice!"

rest parameters

JavaScript

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

sum(1, 2, 3);
// 6

sum(10, 20, 30, 40);
// 100

closures

JavaScript

function makeCounter() {
  let count = 0;
  // count is remembered by the inner functions

  return {
    increment() { count += 1; return count; },
    decrement() { count -= 1; return count; },
    value()     { return count; },
  };
}

const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
// count is private — not accessible outside

higher-order functions

JavaScript

function repeat(times, action) {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeat(3, i => console.log("Step " + i));
// Step 0
// Step 1
// Step 2

Classes

A class is a blueprint for creating objects. Define the shape once, then stamp out as many instances as you need — each with their own data.

basic class

JavaScript

class Animal {
  constructor(name, species) {
    this.name    = name;
    this.species = species;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

const cat = new Animal("Mia", "Cat");
const dog = new Animal("Rex", "Dog");

cat.speak()
// "Mia makes a sound."

dog.name
// "Rex"

private fields

JavaScript

class BankAccount {
  #balance = 0;
  // private — only this class can touch it

  constructor(start) {
    this.#balance = start;
  }

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
account.getBalance();
// 150

// ❌ can't access directly
// account.#balance → SyntaxError

inheritance

JavaScript

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound.`; }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // run Animal's constructor first
    this.breed = breed;
  }

  // override parent method
  speak() { return `${this.name} barks!`; }
}

const dog = new Dog("Rex", "Labrador");

dog.speak()
// "Rex barks!"

dog instanceof Dog    // true
dog instanceof Animal // true

static methods

JavaScript

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  // instance method
  toFahrenheit() {
    return this.celsius * 9/5 + 32;
  }

  // static — call on the class directly
  static fromFahrenheit(f) {
    return new Temperature((f - 32) * 5/9);
  }
}

const boiling = new Temperature(100);
boiling.toFahrenheit()
// 212

// no 'new' needed
const freezing = Temperature.fromFahrenheit(32);
freezing.celsius
// 0

Promises & Async/Await

Some things take time — loading data, waiting on a server. Promises and async/await let your code wait for those things without freezing the whole page.

what is a Promise?

JavaScript

// resolves after a delay
const wait = ms =>
  new Promise(resolve => setTimeout(resolve, ms));

// can succeed or fail
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    if (id > 0) {
      resolve({ id, name: "Alice" });
      // success
    } else {
      reject(new Error("Invalid id"));
      // failure
    }
  });
}

async / await

JavaScript

// without async/await ❌ harder to read
fetchUser(1)
  .then(user => console.log(user.name))
  .catch(err  => console.error(err));

// with async/await ✅ reads like normal code
async function loadUser() {
  const user = await fetchUser(1);
  console.log(user.name);
}

// with error handling
async function loadUserSafely(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (error) {
    console.error("Failed:", error.message);
    return null;
  }
}

Always wrap `await` in try/catch — if the Promise rejects and you don't catch it, your app will crash.

fetch — load data from a server

JavaScript

// GET — load data
async function getUsers() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
  );
  const users = await response.json();
  return users;
}

const users = await getUsers();
users[0].name
// "Leanne Graham"

// POST — send data
async function createUser(data) {
  const response = await fetch("/api/users", {
    method:  "POST",
    headers: { "Content-Type": "application/json" },
    body:    JSON.stringify(data),
  });

  if (!response.ok) {
    throw new Error(`Failed: ${response.status}`);
  }

  return await response.json();
}

Promise.all — run requests in parallel

JavaScript

// ❌ slow — one at a time
const user  = await fetchUser(1);  // ~200ms
const posts = await fetchPosts(1); // ~200ms
// total: ~400ms

// ✅ fast — both at once
const [user, posts] = await Promise.all([
  fetchUser(1),
  fetchPosts(1),
]);
// total: ~200ms

If any Promise in `Promise.all` fails, the whole thing fails. Use `Promise.allSettled()` if you want all results regardless.

Error Handling

Things go wrong. A missing field, a failed request, bad input — JavaScript throws an error and stops. Use try/catch to handle it cleanly instead of letting the whole thing crash.

try / catch / finally

JavaScript

try {
  const data = JSON.parse("{ bad json }");
  processData(data);

} catch (error) {
  // runs if try throws
  console.error("Failed:", error.message);

} finally {
  // always runs
  hideLoadingSpinner();
}

custom errors

JavaScript

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name  = "ValidationError";
    this.field = field;
  }
}

try {
  throw new ValidationError(
    "email",
    "Email format is invalid"
  );
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(`"${error.field}": ${error.message}`);
  } else {
    throw error; // unexpected — re-throw it
  }
}

Map & Set

Map is like an object but any value can be a key. Set is like an array but every value must be unique. Both are built-in and work great for specific situations.

Map

JavaScript

const map = new Map();

map.set("name", "Alice");
map.set(1, "number key");
map.set(true, "boolean key");

map.get("name") // "Alice"
map.has(1)      // true
map.size        // 3
map.delete(true)

// loop over entries
for (const [key, value] of map) {
  console.log(key, "→", value);
}

Set

JavaScript

// duplicates removed automatically
const set = new Set([1, 2, 3, 2, 1]);
// {1, 2, 3}

set.add(4);    // {1, 2, 3, 4}
set.has(2);    // true
set.delete(2); // {1, 3, 4}
set.size;      // 3

// remove duplicates from array
const nums   = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
// [1, 2, 3]

Most common use: remove duplicates with `[...new Set(array)]`

Modules — Import & Export

Split your code across multiple files and share what's needed between them. It keeps things organised and easier to maintain as your project grows.

exporting from a file

JavaScript

// math.js — named exports
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

// logger.js — default export
export default class Logger {
  log(msg) {
    console.log(`[LOG] ${msg}`);
  }
}

importing from another file

JavaScript

// default — no {}
import Logger from "./logger.js";

// named — need {}
import { add, PI } from "./math.js";

// rename on import
import { add as sum } from "./math.js";

// import everything
import * as MathUtils from "./math.js";
MathUtils.add(1, 2) // 3
MathUtils.PI        // 3.14159

// dynamic — load only when needed
async function loadChart() {
  const { Chart } = await import("./chart.js");
  return new Chart();
}

DOM & Events

The DOM is how JavaScript reads and changes what's on the page. Events let you respond to clicks, typing, scrolling — anything the user does.

select elements

JavaScript

// first match only
document.querySelector(".btn")
document.querySelector("#submit")
document.querySelector("input[type='email']")

// all matches
const cards = document.querySelectorAll(".card");
cards.forEach(card => {
  console.log(card.textContent);
});

change text and styles

JavaScript

const el = document.querySelector("#title");

// change text
el.textContent = "New Title";

// classes
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
// adds if missing, removes if there

// inline styles
el.style.color   = "red";
el.style.display = "none";

Use `textContent` for plain text — it's safe. Avoid `innerHTML` with user data, it can run malicious scripts.

create and remove elements

JavaScript

// create a new element
const card = document.createElement("div");
card.textContent = "Hello from JS!";
card.className   = "card";

// add to page
document.body.appendChild(card);

// remove it
card.remove();

listen for events

JavaScript

const btn = document.querySelector("#submit");

btn.addEventListener("click", (event) => {
  event.preventDefault();
  // stops form from submitting
  console.log("Clicked!");
});

// common events:
// "click" "input" "submit"
// "keydown" "scroll" "load"

// event delegation — one listener for many
document.querySelector("#list")
  .addEventListener("click", (event) => {
    const item = event.target.closest("li");
    if (item) {
      console.log("Clicked:", item.textContent);
    }
  });

Handy Patterns

Short techniques you'll see in real JavaScript code. None of these are complicated once you know what they do — and you'll spot them everywhere after that.

nullish coalescing ??

JavaScript

const name = user.name ?? "Anonymous";
// "Anonymous" only if null/undefined

// why not || ?
const score  = 0 || 10;
// 10 ← wrong, 0 is valid!

const score2 = 0 ?? 10;
// 0 ← correct

Prefer `??` over `||` for fallbacks. With `||`, valid values like `0` or `''` get wrongly replaced.

optional chaining ?.

JavaScript

// without ?. — crashes if address is missing
// const city = user.address.city; ❌

// with ?. — returns undefined safely
const city  = user?.address?.city;
const first = data?.items?.[0]?.name;
const val   = obj?.method?.();

// combine with ?? for a clean fallback
const display =
  user?.profile?.displayName
  ?? user?.name
  ?? "Guest";

debounce

JavaScript

function debounce(fn, delayMs) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(
      () => fn(...args),
      delayMs
    );
  };
}

// fires 300ms after user stops typing
const onSearch = debounce((query) => {
  fetchResults(query);
}, 300);

input.addEventListener("input", e => {
  onSearch(e.target.value);
});

deep clone

JavaScript

const original = {
  name: "Alice",
  address: { city: "London" }
};

// shallow — nested still shared ❌
const shallow = { ...original };
shallow.address.city = "Paris";
original.address.city
// "Paris" — oops!

// deep clone — fully independent ✅
const deep = structuredClone(original);
deep.address.city = "Paris";
original.address.city
// "London" — safe

short-circuit operators

JavaScript

// run only if condition is true
isLoggedIn && showDashboard();

// fallback if value is missing
const label = config.label || "Default";

// assign only if null/undefined
user.role ??= "viewer";

Use these for simple one-liners. For anything more complex, a full `if` statement is easier to read.

Was this helpful?

No login required to share feedback

More Cheatsheets

Keep your reference handy

Explore more zero-to-hero cheatsheets for the tools you use daily.