Skip to the content.

← Back to Index

JavaScript Cheat Sheet


Basics

let x = 10;           // block scoped (mutable)
const y = 20;         // block scoped (immutable)
var z = 30;           // function scoped — avoid if possible

typeof x;             // "number"
typeof null;          // "object" (legacy bug)

Falsy values: false, 0, '', null, undefined, NaN


Functions

function sum(a, b) {
  return a + b;
}

const multiply = (a, b) => a * b;

Objects

const user = {
  name: "Rafael",
  age: 41,
  speak() {
    console.log(`Hi, I'm ${this.name}`);
  }
};

user["name"];      // "Rafael"
user.speak();      // uses this

Arrays

const list = [1, 2, 3];

list.map(x => x * 2);       // [2, 4, 6]
list.filter(x => x > 1);    // [2, 3]
list.reduce((a, b) => a + b, 0); // 6

Equality

1 == "1";   // true      (type coercion)
1 === "1";  // false     (strict)

Always prefer === and !==


Destructuring

const [a, b] = [1, 2];
const { name, age } = user;

With defaults:

const { lang = "en" } = settings;

Spread & Rest

const arr = [1, 2, 3];
const clone = [...arr];

function logAll(...args) {
  console.log(args);
}

Classes & Inheritance

The prototype is king

img.png

Classes are just syntactic sugar

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

  speak() {
    console.log(`${this.name} makes noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

Modules

// Exporting
export function add(a, b) { return a + b; }
export default class Something { ... }

// Importing
import { add } from './math.js';
import Something from './thing.js';

Use "type": "module" in package.json to enable ESM.


Promises & Async/Await

async function fetchData() {
  const res = await fetch('/api');
  const data = await res.json();
  return data;
}

fetchData().then(console.log);

Handle errors with try/catch or .catch().


Error Handling

try {
  throw new Error("Nope");
} catch (e) {
  console.error(e.message);
}

Useful APIs

Object.keys(obj);    // array of keys
Object.values(obj);  // array of values
Object.entries(obj); // [[key, value], ...]

Math.random();       // 0..1
Date.now();          // timestamp in ms

Event Loop & Execution


Gotchas


Best Practices