Skip to content

cheatnotes/javascript-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

JavaScript Comprehensive Cheatsheet

Complete reference covering variables, functions, arrays, objects, ES6+, DOM, async/await, promises, classes, modules & more. From basics to advanced JS concepts with clear code examples. Perfect quick guide for developers of all levels. Save & bookmark!

Table of Contents

  1. Variables & Data Types
  2. Operators
  3. Control Flow
  4. Functions
  5. Arrays
  6. Objects
  7. Strings
  8. ES6+ Features
  9. DOM Manipulation
  10. Events
  11. Asynchronous JavaScript
  12. Error Handling
  13. Classes & OOP
  14. Modules
  15. Built-in Methods
  16. Browser APIs
  17. Tips & Best Practices

1. Variables & Data Types

Variable Declarations

// var - function scoped, can be redeclared
var name = "John";

// let - block scoped, can be reassigned
let age = 25;

// const - block scoped, cannot be reassigned
const PI = 3.14159;

Primitive Data Types

// String
let str = "Hello";
let str2 = 'World';
let str3 = `Template ${str}`;  // Template literal

// Number
let num = 42;
let float = 3.14;
let infinity = Infinity;
let notANumber = NaN;

// Boolean
let isTrue = true;
let isFalse = false;

// Undefined
let undefinedVar;

// Null
let nullVar = null;

// Symbol (ES6)
let sym = Symbol('description');

// BigInt (ES2020)
let bigNum = 9007199254740991n;

Type Checking

typeof "Hello"        // "string"
typeof 42            // "number"
typeof true          // "boolean"
typeof undefined     // "undefined"
typeof null          // "object" (bug!)
typeof Symbol()      // "symbol"
typeof {}            // "object"
typeof []            // "object"
typeof function(){}  // "function"

// Better type checking
Array.isArray([])           // true
Object.prototype.toString.call([])  // "[object Array]"

Type Conversion

// String conversion
String(123)          // "123"
(123).toString()     // "123"
123 + ""            // "123"

// Number conversion
Number("123")       // 123
parseInt("123px")   // 123
parseFloat("3.14")  // 3.14
+"123"              // 123

// Boolean conversion
Boolean(1)          // true
Boolean(0)          // false
Boolean("")         // false
!!"text"            // true

2. Operators

Arithmetic Operators

let a = 10 + 5;    // 15 (Addition)
let b = 10 - 5;    // 5 (Subtraction)
let c = 10 * 5;    // 50 (Multiplication)
let d = 10 / 5;    // 2 (Division)
let e = 10 % 3;    // 1 (Modulus/Remainder)
let f = 2 ** 3;    // 8 (Exponentiation ES6)
let g = 10;
g++;               // 11 (Increment)
g--;               // 10 (Decrement)

Comparison Operators

// Equality
5 == "5"           // true (loose equality)
5 === "5"          // false (strict equality)
5 != "5"           // false
5 !== "5"          // true

// Relational
5 > 3              // true
5 < 3              // false
5 >= 5             // true
5 <= 4             // false

Logical Operators

// AND (&&)
true && true       // true
true && false      // false

// OR (||)
true || false      // true
false || false     // false

// NOT (!)
!true              // false
!false             // true

// Nullish Coalescing (??)
null ?? "default"         // "default"
undefined ?? "default"    // "default"
0 ?? "default"           // 0 (only null/undefined)

// Optional Chaining (?.)
const user = { name: "John" };
user?.address?.street     // undefined (no error)

Assignment Operators

let x = 10;
x += 5;   // x = x + 5  (15)
x -= 5;   // x = x - 5  (10)
x *= 2;   // x = x * 2  (20)
x /= 2;   // x = x / 2  (10)
x %= 3;   // x = x % 3  (1)
x **= 2;  // x = x ** 2 (1)

Ternary Operator

let result = condition ? valueIfTrue : valueIfFalse;
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";

3. Control Flow

If-Else Statements

if (condition) {
  // code
} else if (anotherCondition) {
  // code
} else {
  // code
}

Switch Statement

switch(expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // code
}

Loops

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

// While loop
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// Do-while loop
let j = 0;
do {
  console.log(j);
  j++;
} while (j < 5);

// For...of (iterables: arrays, strings, maps, sets)
const arr = [1, 2, 3];
for (let value of arr) {
  console.log(value);
}

// For...in (object properties)
const obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
  console.log(key, obj[key]);
}

Break & Continue

// Break - exits loop
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0,1,2,3,4
}

// Continue - skips iteration
for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i); // 0,1,3,4
}

4. Functions

Function Declarations

// Function Declaration (hoisted)
function greet(name) {
  return `Hello, ${name}!`;
}

// Function Expression
const greet = function(name) {
  return `Hello, ${name}!`;
};

// Arrow Function (ES6)
const greet = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const square = x => x * x;
const noArgs = () => "Hello";
const returnObject = () => ({ key: "value" });

Parameters

// Default parameters
function greet(name = "Guest") {
  return `Hello, ${name}!`;
}

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3, 4); // 10

// Arguments object (old way)
function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

Callback Functions

function processUserInput(callback) {
  const name = "John";
  callback(name);
}

processUserInput(function(name) {
  console.log(`Hello ${name}`);
});

// Or with arrow function
processUserInput(name => console.log(`Hello ${name}`));

IIFE (Immediately Invoked Function Expression)

(function() {
  console.log("I run immediately!");
})();

// With arrow function
(() => {
  console.log("I also run immediately!");
})();

Closures

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

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

5. Arrays

Array Creation

const arr1 = [1, 2, 3];
const arr2 = new Array(3); // [empty × 3]
const arr3 = Array.from("hello"); // ['h','e','l','l','o']
const arr4 = Array.of(1, 2, 3); // [1,2,3]

Array Methods

Adding/Removing Elements

let arr = [1, 2, 3];

// End
arr.push(4);        // [1,2,3,4] - adds to end
arr.pop();          // [1,2,3] - removes from end

// Beginning
arr.unshift(0);     // [0,1,2,3] - adds to beginning
arr.shift();        // [1,2,3] - removes from beginning

// Middle
arr.splice(1, 0, "a");  // [1,'a',2,3] - insert at index 1
arr.splice(1, 1);       // [1,2,3] - remove 1 element at index 1
arr.splice(1, 1, "b");  // [1,'b',3] - replace

// Slice (non-mutating)
arr.slice(1, 3);    // [2,3] - extract portion

Searching & Finding

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

// Index
arr.indexOf(3);        // 2 (first occurrence)
arr.lastIndexOf(3);    // 5 (last occurrence)
arr.includes(3);       // true

// Finding elements
arr.find(x => x > 3);        // 4 (first match)
arr.findIndex(x => x > 3);   // 3 (index of first match)
arr.filter(x => x > 3);      // [4,5] (all matches)

// Testing
arr.every(x => x > 0);  // true (all match?)
arr.some(x => x > 4);   // true (any match?)

Transforming Arrays

const arr = [1, 2, 3];

// Map - transform each element
arr.map(x => x * 2);  // [2,4,6]

// Filter - keep elements that pass test
arr.filter(x => x > 1);  // [2,3]

// Reduce - accumulate values
arr.reduce((acc, val) => acc + val, 0);  // 6

// Flat - flatten nested arrays
[1, [2, [3]]].flat(2);  // [1,2,3]

// FlatMap - map then flat
[1, 2, 3].flatMap(x => [x, x * 2]);  // [1,2,2,4,3,6]

Sorting & Reversing

const arr = [3, 1, 4, 1, 5];

arr.sort();                 // [1,1,3,4,5] (alphabetical)
arr.sort((a, b) => a - b);  // [1,1,3,4,5] (numerical ascending)
arr.sort((a, b) => b - a);  // [5,4,3,1,1] (numerical descending)
arr.reverse();              // [5,1,4,1,3]

Other Array Methods

const arr = [1, 2, 3];

// Join
arr.join("-");      // "1-2-3"

// Concat
arr.concat([4, 5]);  // [1,2,3,4,5]

// Fill
arr.fill(0);        // [0,0,0]
[1,2,3].fill(0, 1, 2);  // [1,0,3]

// CopyWithin
[1,2,3,4,5].copyWithin(0, 3);  // [4,5,3,4,5]

6. Objects

Object Creation

// Object literal
const person = {
  name: "John",
  age: 30,
  "full-name": "John Doe"  // special property names need quotes
};

// Constructor
const obj = new Object();
obj.key = "value";

// Object.create()
const proto = { greet() { return "Hello"; } };
const obj2 = Object.create(proto);

Property Access & Manipulation

const obj = { name: "John", age: 30 };

// Access
obj.name;           // "John" (dot notation)
obj["name"];        // "John" (bracket notation)
const key = "name";
obj[key];           // "John" (dynamic access)

// Add/Update
obj.city = "NYC";   // Add new property
obj.age = 31;       // Update existing property

// Delete
delete obj.city;    // Remove property

// Check existence
"name" in obj;                  // true
obj.hasOwnProperty("name");     // true

Object Methods

const obj = { a: 1, b: 2, c: 3 };

// Keys, Values, Entries
Object.keys(obj);      // ['a', 'b', 'c']
Object.values(obj);    // [1, 2, 3]
Object.entries(obj);   // [['a',1], ['b',2], ['c',3]]

// Object spread
const newObj = { ...obj, d: 4 };  // {a:1, b:2, c:3, d:4}

// Object.assign (merge)
Object.assign({}, obj, { c: 30 });  // {a:1, b:2, c:30}

// Freeze & Seal
Object.freeze(obj);   // Cannot add/delete/modify
Object.seal(obj);     // Cannot add/delete, can modify
Object.isFrozen(obj); // true/false
Object.isSealed(obj); // true/false

// Property descriptors
const descriptor = Object.getOwnPropertyDescriptor(obj, 'a');
Object.defineProperty(obj, 'd', {
  value: 4,
  writable: false,
  enumerable: true,
  configurable: false
});

Destructuring

const person = { name: "John", age: 30, city: "NYC" };

// Basic destructuring
const { name, age } = person;

// With alias
const { name: fullName, age: years } = person;

// Default values
const { country = "USA" } = person;

// Rest pattern
const { name, ...rest } = person;  // rest = { age: 30, city: "NYC" }

// Nested destructuring
const user = { id: 1, info: { name: "John", email: "[email protected]" } };
const { info: { name, email } } = user;

Shorthand & Computed Properties

const name = "John";
const age = 30;

// Property shorthand
const person = { name, age };  // { name: "John", age: 30 }

// Method shorthand
const obj = {
  greet() {
    return "Hello!";
  }
};

// Computed property names
const key = "dynamic";
const obj2 = {
  [key]: "value",
  [`computed_${key}`]: "another value"
};

7. Strings

String Methods

const str = "Hello, World!";

// Length
str.length;  // 13

// Case conversion
str.toUpperCase();    // "HELLO, WORLD!"
str.toLowerCase();    // "hello, world!"

// Character access
str.charAt(0);        // "H"
str.charCodeAt(0);    // 72
str[0];               // "H"

// Searching
str.indexOf("World");     // 7
str.lastIndexOf("l");     // 10
str.includes("Hello");    // true
str.startsWith("He");     // true
str.endsWith("!");        // true
str.search(/world/i);     // 7 (regex search)

// Substrings
str.slice(0, 5);          // "Hello"
str.substring(0, 5);      // "Hello"
str.substr(7, 5);         // "World" (deprecated)

// Trimming
"  Hello  ".trim();       // "Hello"
"  Hello  ".trimStart();  // "Hello  "
"  Hello  ".trimEnd();    // "  Hello"

// Padding
"5".padStart(3, "0");     // "005"
"5".padEnd(3, "0");       // "500"

// Replacing
str.replace("World", "JavaScript");  // "Hello, JavaScript!"
str.replace(/l/g, "L");              // "HeLLo, WorLd!"
str.replaceAll("l", "L");            // "HeLLo, WorLd!"

// Splitting & Joining
str.split(", ");          // ["Hello", "World!"]
arr.join(", ");           // "Hello, World!"

// Repeating
"Hi".repeat(3);           // "HiHiHi"

// Template literals
const name = "John";
`Hello, ${name}!`;        // "Hello, John!"
`Sum: ${1 + 2}`;          // "Sum: 3"

Tagged Templates

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => 
    `${result}${str}<strong>${values[i] || ''}</strong>`, '');
}

const name = "John";
const age = 30;
highlight`${name} is ${age} years old`;
// "<strong>John</strong> is <strong>30</strong> years old"

8. ES6+ Features

Spread Operator

// Arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];  // [1,2,3,4,5]
const copy = [...arr1];        // shallow copy

// Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };  // {a:1, b:2, c:3}

// Function arguments
const nums = [1, 2, 3];
sum(...nums);

// Strings
const chars = [..."hello"];  // ['h','e','l','l','o']

Destructuring

// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// a=1, b=2, rest=[3,4,5]

// With defaults
const [x = 0, y = 0] = [1];

// Swapping
let a = 1, b = 2;
[a, b] = [b, a];  // a=2, b=1

// Object destructuring (covered above)

Map & Set

// Map
const map = new Map();
map.set('key', 'value');
map.get('key');        // 'value'
map.has('key');        // true
map.delete('key');
map.size;              // 0
map.clear();

// Iterating Map
for (let [key, value] of map) { }
map.forEach((value, key) => { });

// Set
const set = new Set([1, 2, 3, 3]);  // {1, 2, 3}
set.add(4);
set.has(2);           // true
set.delete(2);
set.size;             // 3

// Set operations
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
new Set([...set1, ...set2]);              // Union: {1,2,3,4}
new Set([...set1].filter(x => set2.has(x))); // Intersection: {2,3}

Promises

// Creating
const promise = new Promise((resolve, reject) => {
  // async operation
  if (success) resolve(data);
  else reject(error);
});

// Consuming
promise
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log("Done"));

// Promise methods
Promise.all([p1, p2, p3]);       // All resolve or one rejects
Promise.allSettled([p1, p2]);    // Wait for all (ES2020)
Promise.race([p1, p2]);          // First to settle
Promise.any([p1, p2]);           // First to resolve (ES2021)
Promise.resolve(value);          // Resolved promise
Promise.reject(error);           // Rejected promise

Classes

class Person {
  // Private field (ES2022)
  #privateField = "private";
  
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // Method
  greet() {
    return `Hi, I'm ${this.name}`;
  }
  
  // Getter
  get info() {
    return `${this.name}, ${this.age}`;
  }
  
  // Setter
  set info(value) {
    [this.name, this.age] = value.split(", ");
  }
  
  // Static method
  static species() {
    return "Homo sapiens";
  }
  
  // Private method
  #privateMethod() {
    return this.#privateField;
  }
}

// Inheritance
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
  
  greet() {
    return `${super.greet()} and I'm in grade ${this.grade}`;
  }
}

9. DOM Manipulation

Selecting Elements

// Single elements
document.getElementById("myId");
document.querySelector(".myClass");
document.querySelector("#myId");

// Multiple elements
document.getElementsByClassName("myClass");  // HTMLCollection (live)
document.getElementsByTagName("div");        // HTMLCollection (live)
document.querySelectorAll(".myClass");       // NodeList (static)

Modifying Elements

const element = document.querySelector("#myId");

// Content
element.textContent = "Hello";
element.innerHTML = "<strong>Hello</strong>";
element.innerText = "Hello";  // respects CSS

// Attributes
element.setAttribute("class", "newClass");
element.getAttribute("class");
element.removeAttribute("class");
element.hasAttribute("class");
element.id = "newId";
element.className = "class1 class2";
element.classList.add("class3");
element.classList.remove("class1");
element.classList.toggle("active");
element.classList.contains("class2");

// Styles
element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.cssText = "color: red; background: blue;";
getComputedStyle(element).color;  // Read computed styles

// Data attributes
element.dataset.myValue;  // <div data-my-value="123">

Creating & Removing Elements

// Create
const div = document.createElement("div");
div.innerHTML = "Hello";

// Clone
const clone = element.cloneNode(true);  // true = deep clone

// Insert
parent.appendChild(div);
parent.append(div, "text");  // Modern
parent.append(div, textNode);
parent.prepend(div);
element.before(div);
element.after(div);

// HTML insertion
element.insertAdjacentHTML("beforebegin", "<p>Before</p>");
element.insertAdjacentHTML("afterbegin", "<p>First child</p>");
element.insertAdjacentHTML("beforeend", "<p>Last child</p>");
element.insertAdjacentHTML("afterend", "<p>After</p>");

// Replace
oldElement.replaceWith(newElement);

// Remove
element.remove();
parent.removeChild(child);

Traversing DOM

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

// Parent
el.parentElement;
el.parentNode;

// Children
el.children;        // HTMLCollection of elements
el.childNodes;      // NodeList including text nodes
el.firstElementChild;
el.lastElementChild;
el.firstChild;
el.lastChild;

// Siblings
el.nextElementSibling;
el.previousElementSibling;
el.nextSibling;
el.previousSibling;

// Check
el.matches(".myClass");  // CSS selector match
el.closest(".parent");   // Nearest ancestor match

10. Events

Event Handling

// Add event listener (preferred)
element.addEventListener("click", function(event) {
  console.log("clicked!", event);
});

// Remove event listener
const handler = (e) => console.log(e);
element.addEventListener("click", handler);
element.removeEventListener("click", handler);

// Inline event (not recommended)
element.onclick = function(event) { };

// Event object properties
event.target;          // Element that triggered event
event.currentTarget;   // Element that listener is attached to
event.type;            // "click", "keydown", etc.
event.preventDefault(); // Prevent default behavior
event.stopPropagation(); // Stop bubbling
event.stopImmediatePropagation(); // Stop all listeners

Common Events

// Mouse events
"click", "dblclick", "mousedown", "mouseup", "mouseenter", "mouseleave", "mouseover", "mouseout", "mousemove"

// Keyboard events
"keydown", "keyup", "keypress"
event.key;      // "Enter", "a", "Escape"
event.code;     // "KeyA", "Enter"
event.keyCode;  // 13 (deprecated but still used)

// Form events
"submit", "change", "input", "focus", "blur", "reset"

// Document/Window events
"load", "DOMContentLoaded", "resize", "scroll", "unload", "beforeunload"

// Touch events
"touchstart", "touchmove", "touchend"

Event Delegation

// Efficient event handling for dynamic content
document.querySelector("#parent").addEventListener("click", function(e) {
  if (e.target.matches(".child-class")) {
    console.log("Child clicked!", e.target);
  }
});

Custom Events

// Create and dispatch
const customEvent = new CustomEvent("myEvent", {
  detail: { message: "Hello!" },
  bubbles: true
});
element.dispatchEvent(customEvent);

// Listen
element.addEventListener("myEvent", (e) => {
  console.log(e.detail.message);
});

11. Asynchronous JavaScript

Callbacks

function fetchData(callback) {
  setTimeout(() => {
    callback(null, "Data received");
  }, 1000);
}

fetchData((error, data) => {
  if (error) console.error(error);
  else console.log(data);
});

// Callback hell example (avoid!)
fetchUser(userId, (user) => {
  fetchPosts(user.id, (posts) => {
    fetchComments(posts[0].id, (comments) => {
      // deeply nested
    });
  });
});

Promises

// Basic promise
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true;
    if (success) resolve("Data");
    else reject("Error");
  }, 1000);
});

fetchData
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log("Done"));

// Promise.all
Promise.all([fetchUser(1), fetchUser(2)])
  .then(([user1, user2]) => { })
  .catch(error => { });

// Promise.race
Promise.race([timeout(5000), fetchData()])
  .then(result => { });

// Promise.allSettled
Promise.allSettled([p1, p2])
  .then(results => {
    results.forEach(result => {
      if (result.status === 'fulfilled') console.log(result.value);
      else console.log(result.reason);
    });
  });

Async/Await

// Basic async function
async function getData() {
  try {
    const response = await fetch("https://api.example.com");
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}

// Parallel execution
async function fetchAll() {
  const [users, posts] = await Promise.all([
    fetchUsers(),
    fetchPosts()
  ]);
  return { users, posts };
}

// Async arrow function
const getData = async () => {
  const data = await fetchData();
  return data;
};

// IIFE with async
(async () => {
  const data = await getData();
  console.log(data);
})();

Fetch API

// GET request
fetch("https://api.example.com/data")
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

// POST request
fetch("https://api.example.com/data", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer token123"
  },
  body: JSON.stringify({ name: "John" })
});

// With async/await
async function postData() {
  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  });
  return response.json();
}

// Response methods
response.json();      // Parse JSON
response.text();      // Parse text
response.blob();      // Get Blob
response.arrayBuffer(); // Get ArrayBuffer
response.ok;          // Status 200-299
response.status;      // HTTP status code

12. Error Handling

Try-Catch

try {
  // Code that might throw
  throw new Error("Something went wrong");
} catch (error) {
  console.error(error.message);
  console.error(error.name);
  console.error(error.stack);
} finally {
  // Always executes
  console.log("Cleanup");
}

Custom Errors

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

throw new ValidationError("Invalid input");

Error Handling in Async Code

// Promise error handling
promise
  .then(result => { })
  .catch(error => console.error(error));

// Async/await error handling
async function example() {
  try {
    await riskyOperation();
  } catch (error) {
    console.error(error);
  }
}

// Global error handling
window.addEventListener("unhandledrejection", event => {
  console.error("Unhandled promise rejection:", event.reason);
});

window.addEventListener("error", event => {
  console.error("Global error:", event.error);
});

13. Classes & OOP

Basic Class

class Animal {
  constructor(name) {
    this.name = name;
    this._speed = 0;  // Convention for "protected"
  }
  
  // Method
  speak() {
    return `${this.name} makes a sound.`;
  }
  
  // Getter
  get speed() {
    return this._speed;
  }
  
  // Setter
  set speed(value) {
    if (value < 0) throw new Error("Negative speed");
    this._speed = value;
  }
  
  // Static method
  static className() {
    return "Animal";
  }
  
  // Static property
  static planet = "Earth";
}

Inheritance

class Dog extends Animal {
  constructor(name, breed) {
    super(name);  // Must call super first
    this.breed = breed;
  }
  
  // Override method
  speak() {
    return `${super.speak()} Woof!`;  // Call parent method
  }
  
  // New method
  fetch() {
    return `${this.name} fetches the stick.`;
  }
}

Private Fields & Methods (ES2022)

class BankAccount {
  #balance = 0;  // Private field
  
  constructor(owner) {
    this.owner = owner;
  }
  
  deposit(amount) {
    this.#balance += amount;
    return this.#balance;
  }
  
  getBalance() {
    return this.#balance;
  }
  
  #privateMethod() {  // Private method
    console.log("Private");
  }
}

Mixins

const flyMixin = {
  fly() {
    return `${this.name} is flying`;
  }
};

const swimMixin = {
  swim() {
    return `${this.name} is swimming`;
  }
};

class Bird extends Animal {
  constructor(name) {
    super(name);
    Object.assign(this, flyMixin);
  }
}

14. Modules

ES6 Modules (Modern)

Exporting

// Named exports (file: math.js)
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Calculator { }

// Or export at end
const PI = 3.14159;
function add(a, b) { return a + b; }
export { PI, add };

// Default export (one per module)
export default class Calculator { }

// Rename export
export { add as sum };

Importing

// Named imports
import { PI, add } from "./math.js";
import { add as sum } from "./math.js";  // Rename
import * as math from "./math.js";       // All as namespace

// Default import
import Calculator from "./math.js";

// Mixed import
import Calculator, { PI, add } from "./math.js";

// Dynamic import (returns promise)
const module = await import("./math.js");
module.add(1, 2);

// Side effects only
import "./styles.css";

CommonJS (Node.js)

// Exporting
module.exports = { add, subtract };
exports.multiply = (a, b) => a * b;

// Importing
const math = require("./math");
const { add, multiply } = require("./math");

15. Built-in Methods

Number Methods

// Conversion and checking
Number.isNaN(NaN);           // true
Number.isFinite(Infinity);   // false
Number.isInteger(5.0);       // true
Number.isSafeInteger(9007199254740991);  // true

// Formatting
(3.14159).toFixed(2);     // "3.14"
(1234.56).toPrecision(4); // "1235"
(255).toString(16);       // "ff" (hex)
(123).toExponential(2);   // "1.23e+2"

// Math
Math.PI;              // 3.14159...
Math.abs(-5);         // 5
Math.ceil(4.2);       // 5
Math.floor(4.9);      // 4
Math.round(4.5);      // 5
Math.max(1, 2, 3);    // 3
Math.min(1, 2, 3);    // 1
Math.pow(2, 3);       // 8
Math.sqrt(16);        // 4
Math.random();        // 0-1 (exclusive)
Math.trunc(3.7);      // 3

Date Methods

// Creation
const now = new Date();
const specific = new Date(2024, 0, 1);  // Jan 1, 2024
const fromString = new Date("2024-01-01");

// Getters
date.getFullYear();     // 2024
date.getMonth();        // 0-11
date.getDate();         // 1-31
date.getDay();          // 0-6 (Sunday-Saturday)
date.getHours();        // 0-23
date.getMinutes();      // 0-59
date.getSeconds();      // 0-59
date.getTime();         // milliseconds since epoch
Date.now();             // current timestamp

// Setters
date.setFullYear(2025);
date.setMonth(5);
date.setDate(15);

// Formatting
date.toString();
date.toISOString();     // "2024-01-01T00:00:00.000Z"
date.toLocaleDateString();
date.toLocaleTimeString();
date.toLocaleString();

// Calculations
const diff = date2 - date1;  // milliseconds

Global Methods

// Encoding/Decoding
encodeURIComponent("Hello World!");   // "Hello%20World!"
decodeURIComponent("Hello%20World!"); // "Hello World!"
btoa("Hello");    // Base64 encode
atob("SGVsbG8="); // Base64 decode

// Parsing
parseInt("42px");         // 42
parseFloat("3.14px");     // 3.14

// Timing
setTimeout(() => { }, 1000);
setInterval(() => { }, 1000);
clearTimeout(id);
clearInterval(id);

16. Browser APIs

Local Storage & Session Storage

// Local Storage (persists)
localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
localStorage.key(0);

// Session Storage (session only)
sessionStorage.setItem("key", "value");
sessionStorage.getItem("key");

// Store objects
const user = { name: "John" };
localStorage.setItem("user", JSON.stringify(user));
const stored = JSON.parse(localStorage.getItem("user"));

Geolocation API

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const { latitude, longitude } = position.coords;
      console.log(latitude, longitude);
    },
    (error) => console.error(error),
    { enableHighAccuracy: true, timeout: 5000 }
  );
  
  // Watch position
  const watchId = navigator.geolocation.watchPosition(
    position => console.log(position.coords)
  );
  navigator.geolocation.clearWatch(watchId);
}

History API

// Navigation
history.back();
history.forward();
history.go(-2);
history.length;

// Push/replace state (SPA routing)
history.pushState({ page: 1 }, "Title", "/page1");
history.replaceState({ page: 2 }, "Title", "/page2");

window.addEventListener("popstate", (event) => {
  console.log(event.state);  // state object
});

Web APIs Summary

// Console API
console.log(), .error(), .warn(), .info(), .debug()
console.table(data)
console.time("label"), console.timeEnd("label")
console.group("label"), console.groupEnd()

// Clipboard API
await navigator.clipboard.writeText("text");
const text = await navigator.clipboard.readText();

// Notifications API
Notification.requestPermission().then(permission => {
  if (permission === "granted") {
    new Notification("Title", { body: "Message" });
  }
});

// Intersection Observer
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // Element is visible
    }
  });
});
observer.observe(element);

// Request Animation Frame
function animate() {
  // Animation logic
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

17. Tips & Best Practices

Variable Naming

// Use camelCase for variables and functions
let firstName = "John";
function calculateTotal() { }

// Use PascalCase for classes
class UserManager { }

// Use UPPER_SNAKE_CASE for constants
const MAX_USERS = 100;
const API_URL = "https://api.example.com";

// Prefix booleans with is, has, should
let isLoading = true;
let hasPermission = false;

Performance Tips

// 1. Cache DOM lookups
const button = document.querySelector("#myButton");
button.addEventListener("click", handler);
button.style.color = "red";

// 2. Use DocumentFragment for batch DOM updates
const fragment = document.createDocumentFragment();
items.forEach(item => {
  const li = document.createElement("li");
  li.textContent = item;
  fragment.appendChild(li);
});
list.appendChild(fragment);

// 3. Debounce/throttle events
function debounce(fn, delay) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 4. Use event delegation
// 5. Avoid memory leaks (clean up event listeners)

Code Quality

// Use strict equality
if (value === null) { }  // Good
if (value == null) { }   // Avoid

// Use const by default, let when needed, never var
const MAX = 100;
let count = 0;

// Use descriptive names
// Bad
const x = getData();
// Good
const userData = fetchUserData();

// Keep functions small and single-purpose
// Handle errors properly
// Use modern ES6+ syntax
// Use optional chaining and nullish coalescing

Common Patterns

// Early returns
function processUser(user) {
  if (!user) return null;
  if (!user.isActive) return null;
  return processUserData(user);
}

// Factory functions
function createUser(name, age) {
  return { name, age, createdAt: Date.now() };
}

// Revealing module pattern
const myModule = (() => {
  const privateVar = "secret";
  function privateMethod() { }
  
  return {
    publicMethod() { },
    publicVar: "visible"
  };
})();

// Chaining
const result = arr
  .filter(x => x > 0)
  .map(x => x * 2)
  .reduce((sum, x) => sum + x, 0);

About

Complete reference covering variables, functions, arrays, objects, ES6+, DOM, async/await, promises, classes, modules & more. From basics to advanced JS concepts with clear code examples.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Generated from cheatnotes/cheatnotes