Skip to content
Codewilds

JavaScript cheat sheet

The essential JavaScript syntax on one page. Every snippet comes from a lesson of our interactive Learn JavaScript course — click "Practise" to write it yourself and get instant feedback.

Last updated on .

Fundamentals

JavaScript Variables: let, const and Data Types

Learn how to declare JavaScript variables with let and const, when to use each, and the basic data types: strings, numbers and booleans.

const heroName = "Ada";
let score = 0;

console.log(heroName); // Ada
console.log(score);    // 0
Practise: JavaScript Variables: let, const and Data Types

JavaScript Numbers and Math Operators

Do math in JavaScript: arithmetic operators, remainder with %, exponents, rounding with the Math object and the classic floating-point gotchas.

const gold = 150;
const price = 19.99;
console.log(typeof gold, typeof price); // number number
Practise: JavaScript Numbers and Math Operators

JavaScript Strings and Template Literals

Work with JavaScript strings: template literals, length, indexes, slice, trim, toUpperCase, includes, repeat and other essential string methods.

const realm = "Scriptoria";
console.log(realm.length); // 10
console.log(realm[0]);     // S
console.log(realm[3]);     // i
console.log(realm.at(-1)); // a (negative indexes count from the end)
Practise: JavaScript Strings and Template Literals

JavaScript if/else Statements and Comparison Operators

Make decisions in JavaScript with if, else if and else, compare values with === and !==, combine conditions with && and ||, and spot truthy values.

console.log(5 > 3);   // true
console.log(5 < 3);   // false
console.log(5 >= 5);  // true
console.log(4 <= 3);  // false
console.log(5 === 5); // true  (strictly equal)
console.log(5 !== 3); // true  (strictly not equal)
Practise: JavaScript if/else Statements and Comparison Operators

JavaScript Loops: for and while

Repeat code with JavaScript for and while loops, use break and continue, loop over the characters of a string and avoid off-by-one errors.

for (let i = 1; i <= 3; i++) {
  console.log(`Round ${i}`);
}
// Round 1
// Round 2
// Round 3
Practise: JavaScript Loops: for and while

Functions

JavaScript Functions: Parameters and Return Values

Learn how JavaScript functions work: declare and call them, pass parameters, return values and give parameters default values.

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Ada"));   // Hello, Ada!
console.log(greet("Linus")); // Hello, Linus!
Practise: JavaScript Functions: Parameters and Return Values

JavaScript Arrow Functions Explained

Write shorter JavaScript functions with arrow syntax: implicit returns, parameters, function expressions and when arrow functions behave differently.

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

console.log(add(2, 3)); // 5
Practise: JavaScript Arrow Functions Explained

JavaScript Scope and Closures

Understand JavaScript scope (global, function and block) and closures: functions that remember variables, used for counters and private state.

const realm = "Scriptoria"; // global

function enterTavern() {
  const drink = "cider";    // function scope
  if (realm === "Scriptoria") {
    const song = "ballad";  // block scope
    console.log(drink, song); // cider ballad
  }
  // console.log(song); // ReferenceError: song is not defined
}

enterTavern();
// console.log(drink); // ReferenceError: drink is not defined
Practise: JavaScript Scope and Closures

JavaScript Callbacks and Higher-Order Functions

Learn JavaScript callbacks and higher-order functions: pass functions as arguments, call them later and build flexible, reusable helpers.

function levelUp(level, notify) {
  const newLevel = level + 1;
  notify(`You reached level ${newLevel}!`);
  return newLevel;
}

levelUp(4, (message) => console.log(message));
// You reached level 5!
levelUp(9, (message) => console.log(`*** ${message.toUpperCase()} ***`));
// *** YOU REACHED LEVEL 10! ***
Practise: JavaScript Callbacks and Higher-Order Functions

Arrays

JavaScript Arrays: Methods and Loops for Beginners

Learn JavaScript arrays: indexes and length, push, pop, slice, includes and indexOf, and looping with for...of and forEach.

const party = ["Ada", "Linus", "Grace"];

console.log(party[0]);     // Ada
console.log(party[2]);     // Grace
console.log(party.length); // 3
console.log(party[3]);     // undefined (no item there)
console.log(party.at(-1)); // Grace (negative indexes count from the end)
Practise: JavaScript Arrays: Methods and Loops for Beginners

JavaScript Array map, filter and reduce

Master JavaScript's map, filter and reduce: transform arrays, keep matching items, combine values into one result and chain them together.

const prices = [10, 25, 40];
const withTax = prices.map((price) => price * 1.2);
console.log(withTax); // [ 12, 30, 48 ]

const names = ["ada", "linus"];
console.log(names.map((name) => name.toUpperCase())); // [ 'ADA', 'LINUS' ]
Practise: JavaScript Array map, filter and reduce

JavaScript Array find, some, every and sort

Search and order JavaScript arrays with find, findIndex, some, every and sort, including compare functions and the default sort trap.

const levels = [3, 18, 7, 25];

console.log(levels.find((level) => level > 10)); // 18
console.log(levels.find((level) => level > 99)); // undefined
Practise: JavaScript Array find, some, every and sort

JavaScript Spread Operator and Array Destructuring

Use the JavaScript spread operator to copy and merge arrays, rest parameters to accept any number of arguments, and destructuring to unpack values.

const warriors = ["Conan", "Xena"];
const mages = ["Merlin"];

const party = [...warriors, ...mages];
console.log(party); // [ 'Conan', 'Xena', 'Merlin' ]

const copy = [...warriors];
const withHealer = [...warriors, "Mercy"]; // add an item without mutating
console.log(warriors); // [ 'Conan', 'Xena' ] (unchanged)
Practise: JavaScript Spread Operator and Array Destructuring

Objects

JavaScript Objects: Properties, Methods and this

Learn JavaScript objects: create object literals, read and update properties with dot and bracket notation, write methods and understand this.

const hero = {
  name: "Ada",
  level: 7,
  isOnline: true,
  inventory: ["sword", "map"],
};
Practise: JavaScript Objects: Properties, Methods and this

JavaScript Object Destructuring and Spread

Unpack JavaScript objects with destructuring, set default values, collect the rest, and copy or merge objects immutably with the spread operator.

const hero = { name: "Ada", level: 7, guild: "Coders" };

const { name, level } = hero;
console.log(name, level); // Ada 7
Practise: JavaScript Object Destructuring and Spread

JavaScript Object.keys, Object.entries and JSON

Loop over JavaScript objects with Object.keys, values and entries, rebuild them with Object.fromEntries, and convert data with JSON.stringify and JSON.parse.

const stats = { str: 12, dex: 9, int: 15 };

console.log(Object.keys(stats));    // [ 'str', 'dex', 'int' ]
console.log(Object.values(stats));  // [ 12, 9, 15 ]
console.log(Object.entries(stats)); // [ [ 'str', 12 ], [ 'dex', 9 ], [ 'int', 15 ] ]
Practise: JavaScript Object.keys, Object.entries and JSON

JavaScript Map and Set

Learn when to use JavaScript Map and Set instead of objects and arrays: unique values, fast lookups, any type of key and removing duplicates.

const visitors = new Set();
visitors.add("Ada");
visitors.add("Linus");
visitors.add("Ada"); // ignored: already in the set

console.log(visitors.size);          // 2
console.log(visitors.has("Linus"));  // true
visitors.delete("Linus");
console.log(visitors);               // Set(1) { 'Ada' }
Practise: JavaScript Map and Set

Classes & Errors

JavaScript Classes: Constructors, Getters and Setters

Learn JavaScript classes: constructors, methods, class fields, private #fields, and getters and setters that validate and compute values.

class Monster {
  constructor(name, hp) {
    this.name = name;
    this.hp = hp;
  }

  roar() {
    return `${this.name} roars!`;
  }
}

const goblin = new Monster("Goblin", 30);
const troll = new Monster("Troll", 120);

console.log(goblin.roar()); // Goblin roars!
console.log(troll.hp);      // 120
console.log(goblin instanceof Monster); // true
Practise: JavaScript Classes: Constructors, Getters and Setters

JavaScript Inheritance: extends, super and static

Reuse code with JavaScript class inheritance: extends, super(), overriding methods, calling parent methods with super, and static methods and fields.

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

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

class Dog extends Animal {
  fetch() {
    return `${this.name} fetches the stick!`;
  }
}

const rex = new Dog("Rex");
console.log(rex.speak()); // Rex makes a sound. (inherited from Animal)
console.log(rex.fetch()); // Rex fetches the stick!
console.log(rex instanceof Dog, rex instanceof Animal); // true true
Practise: JavaScript Inheritance: extends, super and static

JavaScript Error Handling: try, catch and Custom Errors

Handle JavaScript errors with try, catch and finally, throw your own errors, and create custom error classes by extending Error.

const hero = null;
console.log(hero.name); // TypeError: Cannot read properties of null (reading 'name')
Practise: JavaScript Error Handling: try, catch and Custom Errors

Async JavaScript

The JavaScript Event Loop and setTimeout

Understand the JavaScript event loop: the call stack, task queue and microtasks, and schedule code for later with setTimeout and setInterval.

console.log("Brewing potion...");

setTimeout(() => {
  console.log("Potion ready!");
}, 1000);

console.log("Meanwhile, sharpening sword.");
Practise: The JavaScript Event Loop and setTimeout

JavaScript Promises: then, catch and Chaining

Learn JavaScript promises: create them with new Promise, handle results with then, catch and finally, chain async steps and handle errors.

function rollDice() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const roll = Math.floor(Math.random() * 6) + 1;
      if (roll === 1) {
        reject(new Error("Critical failure!"));
      } else {
        resolve(roll);
      }
    }, 500);
  });
}
Practise: JavaScript Promises: then, catch and Chaining

JavaScript async/await and Promise.all

Write clean asynchronous JavaScript with async/await, handle errors with try/catch, and run tasks in parallel with Promise.all and Promise.allSettled.

async function getAnswer() {
  return 42;
}

getAnswer().then((value) => console.log(value)); // 42
Practise: JavaScript async/await and Promise.all