JavaScript Cheat Sheet

Variables (var, let, const)

var is function-scoped; let and const are block-scoped. Use const by default unless reassignment is needed.

var a = 1;
let b = 2;
const c = 3;

Data Types

Primitive types: string, number, boolean, null, undefined, symbol, bigint.

let str = "Hello";
let num = 42;
let isTrue = true;
let nothing = null;
let notDefined;

Operators

Arithmetic (+, -, *, /), Comparison (==, ===, !=, !==), Logical (&&, ||, !).

let x = 5 + 3;
let isEqual = 5 === "5"; // false
let logic = true && false;

Type Coercion & Conversion

Automatic (coercion) or manual (conversion).

let n = "42";
let num = Number(n);
console.log("5" + 1); // "51" (coercion)

Template Literals

Use backticks and ${} for interpolation.

let name = "Alice";
let message = `Hello, ${name}!`;

Comments

// This is a single-line comment
/* This is a 
   multi-line comment */

Control Flow

if / else / switch

if (x > 0) {
  console.log("Positive");
} else {
  console.log("Not positive");
}

switch(day) {
  case "Mon": console.log("Start"); break;
  default: console.log("Other");
}

Loops

for (let i = 0; i < 5; i++) {
  console.log(i);
}

while (x > 0) {
  x--;
}

for (let key in obj) {}
for (let value of arr) {}

break / continue

for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  if (i % 2 === 0) continue;
}

Functions

Function Declaration / Expression

function greet() { return "Hi"; }
const sayHi = function() { return "Hi"; };

Arrow Functions

const add = (a, b) => a + b;

Default & Rest Parameters

function sum(a = 1, ...rest) {
  return a + rest.length;
}

Callback Functions

arr.forEach(function(item) {
  console.log(item);
});

Closures

function outer() {
  let count = 0;
  return function() {
    return ++count;
  }
}

IIFE

(function() {
  console.log("Run immediately");
})();

Data Structures

Arrays

let arr = [1, 2, 3];
arr.map(x => x * 2);
arr.filter(x => x > 1);
arr.reduce((a, b) => a + b);

Objects

let obj = { a: 1, b: 2 };
Object.keys(obj);
Object.values(obj);
Object.entries(obj);

Advanced Concepts

// this keyword
function show() { console.log(this); }

// Scope & Hoisting
console.log(a); var a = 5;

// Strict Mode
"use strict";

// Destructuring
let [a, b] = [1, 2];
let { x, y } = { x: 1, y: 2 };

// Spread & Rest
let arr1 = [1, 2];
let arr2 = [...arr1, 3];

// Optional Chaining
obj?.prop?.sub

// Nullish Coalescing
let val = input ?? "default";

Asynchronous JavaScript

// Callbacks
setTimeout(() => console.log("Done"), 1000);

// Promises
fetch(url)
  .then(res => res.json())
  .catch(err => console.error(err));

// async/await
async function getData() {
  try {
    let res = await fetch(url);
    let data = await res.json();
  } catch (err) {
    console.error(err);
  }
}

Browser APIs

// DOM
let el = document.getElementById("id");
el.textContent = "Hello";

// Events
el.addEventListener("click", () => alert("Clicked"));

// Storage
localStorage.setItem("key", "value");
sessionStorage.getItem("key");

// Fetch
fetch("/api").then(r => r.json());

// Console
console.log("msg");
console.table([1, 2, 3]);

Error Handling

try {
  throw new Error("Oops");
} catch (e) {
  console.error(e.message);
} finally {
  console.log("Always runs");
}

Utilities

// JSON
let obj = JSON.parse('{"a":1}');
let str = JSON.stringify(obj);

// Date
let now = new Date();

// Math
Math.random();
Math.floor(4.7);

// Regex
let match = "hello".match(/h/);

ES6+ Features

// Modules
// file1.js
export const x = 1;
// file2.js
import { x } from "./file1.js";

// Classes
class Person {
  constructor(name) { this.name = name; }
  greet() { return `Hi ${this.name}`; }
}

// Enhanced Object Literals
let a = 1;
let obj = { a, greet() { return "Hi"; } };

// Map / Set
let m = new Map();
m.set("key", "value");
let s = new Set([1, 2]);

Misc

// Short-circuit Evaluation
let val = input || "default";

// Event Loop
setTimeout(() => console.log("macro"));
Promise.resolve().then(() => console.log("micro"));

// Debounce
function debounce(fn, delay) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(fn, delay);
  };
}

// Throttle
function throttle(fn, limit) {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      fn();
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}