RefPad

JavaScript

Table of Contents

  1. Variable / Constant Declaration
  2. Data Types
  3. Operators
  4. String Operations
  5. Array Operations
  6. Object Operations
  7. Control Flow
  8. Functions
  9. Spread / Rest Syntax
  10. Destructuring
  11. Async Processing
  12. Error Handling
  13. Classes
  14. Modules
  15. Useful Methods

1. Variable / Constant Declaration

// Constant (cannot be reassigned — preferred)
const name = "Alice";
 
// Variable (can be reassigned)
let count = 0;
count = 1;
 
// var is avoided (function-scoped and has hoisting issues)
var old = "avoid";

Scope Differences

function example() {
  if (true) {
    var a = "var";   // function-scoped → accessible outside the if block
    let b = "let";   // block-scoped → not accessible outside the if block
    const c = "const"; // block-scoped
  }
  console.log(a); // "var"
  console.log(b); // ReferenceError
}

2. Data Types

Primitive Types

TypeExampleDescription
string"hello", 'world'String
number42, 3.14, NaN, InfinityNumber (integer or decimal)
bigint9007199254740991nLarge integer
booleantrue, falseBoolean
nullnullExplicitly no value
undefinedundefinedUninitialized / not defined
symbolSymbol("id")Unique identifier

Type Checking

typeof "hello"      // "string"
typeof 42           // "number"
typeof true         // "boolean"
typeof undefined    // "undefined"
typeof null         // "object"  ← historical bug; use === null for null checks
typeof []           // "object"
typeof {}           // "object"
typeof function(){} // "function"
 
// Check for array
Array.isArray([1, 2, 3]); // true
 
// Null check
const value = null;
value === null; // true

Type Conversion

// String → Number
Number("42");     // 42
parseInt("42px"); // 42
parseFloat("3.14px"); // 3.14
+"42";            // 42 (unary + operator)
 
// Number → String
String(42);       // "42"
(42).toString();  // "42"
`${42}`;          // "42" (template literal)

3. Operators

Comparison Operators

// === compares value AND type (recommended)
1 === 1;     // true
1 === "1";   // false
 
// == performs type coercion (not recommended)
1 == "1";    // true ← can cause unexpected behavior
 
// Others
1 !== 2;     // true
1 > 0;       // true
1 >= 1;      // true

Logical Operators

true && false; // false (AND)
true || false; // true (OR)
!true;         // false (NOT)
 
// Short-circuit evaluation
const name = user && user.name;      // undefined if user is falsy
const label = name || "Anonymous";   // "Anonymous" if name is falsy
 
// Nullish Coalescing (only null / undefined)
const value = data ?? "default";     // right side only when data is null/undefined

Optional Chaining

const user = { profile: { name: "Alice" } };
 
user?.profile?.name;       // "Alice"
user?.address?.city;       // undefined (no error)
user?.getName?.();         // safe even if method doesn't exist
arr?.[0];                  // optional chaining on arrays

4. String Operations

const str = "Hello, World!";
 
// Length
str.length;             // 13
 
// Search
str.includes("World"); // true
str.startsWith("He");  // true
str.endsWith("!");     // true
str.indexOf("o");      // 4 (first occurrence)
str.lastIndexOf("o");  // 8 (last occurrence)
 
// Extraction
str.slice(7, 12);      // "World"
str.slice(-6);         // "orld!"
 
// Transformation
str.toUpperCase();     // "HELLO, WORLD!"
str.toLowerCase();     // "hello, world!"
str.replace("World", "JS"); // "Hello, JS!"
str.replaceAll("l", "L");   // "HeLLo, WorLd!"
 
// Trim / split / join
"  hello  ".trim();         // "hello"
"  hello  ".trimStart();    // "hello  "
"  hello  ".trimEnd();      // "  hello"
"a,b,c".split(",");         // ["a", "b", "c"]
["a", "b", "c"].join("-");  // "a-b-c"
 
// Repeat / pad
"ha".repeat(3);             // "hahaha"
"5".padStart(3, "0");       // "005"
"5".padEnd(3, "0");         // "500"

Template Literals

const name = "Alice";
const age = 30;
 
// Embed expressions
const greeting = `Hello, ${name}! You are ${age} years old.`;
 
// Multi-line
const multiline = `
  Line 1
  Line 2
  Line 3
`.trim();
 
// Expressions are supported
const result = `Total: ${1 + 2 + 3}`;

5. Array Operations

Basic Operations

const arr = [1, 2, 3, 4, 5];
 
arr.length;           // 5
arr[0];               // 1
arr.at(-1);           // 5 (from the end)
 
// Add / remove
arr.push(6);          // add to end → [1,2,3,4,5,6]
arr.pop();            // remove from end and return it
arr.unshift(0);       // add to beginning
arr.shift();          // remove from beginning and return it
arr.splice(1, 2);     // remove 2 elements starting at index 1
 
// Search
arr.indexOf(3);       // 2
arr.includes(3);      // true
arr.find(x => x > 3);      // 4 (first matching element)
arr.findIndex(x => x > 3); // 3 (index of first match)

Higher-Order Functions (Immutable Operations)

const numbers = [1, 2, 3, 4, 5];
 
// map: transform each element into a new array
numbers.map(n => n * 2);           // [2, 4, 6, 8, 10]
 
// filter: return a new array of elements that pass the test
numbers.filter(n => n % 2 === 0);  // [2, 4]
 
// reduce: reduce array to a single value
numbers.reduce((acc, n) => acc + n, 0); // 15
 
// forEach: iterate for side effects (no return value)
numbers.forEach(n => console.log(n));
 
// find / some / every
numbers.find(n => n > 3);          // 4
numbers.some(n => n > 4);          // true (at least one passes)
numbers.every(n => n > 0);         // true (all pass)
 
// flat / flatMap
[[1, 2], [3, 4]].flat();           // [1, 2, 3, 4]
[1, 2, 3].flatMap(n => [n, n * 2]); // [1, 2, 2, 4, 3, 6]

Sort / Concat / Slice

const arr = [3, 1, 4, 1, 5];
 
// Numeric sort requires a comparator
[...arr].sort((a, b) => a - b);    // [1, 1, 3, 4, 5] (ascending)
[...arr].sort((a, b) => b - a);    // [5, 4, 3, 1, 1] (descending)
 
// String sort
["banana", "apple", "cherry"].sort(); // ["apple", "banana", "cherry"]
 
// slice: returns a new array (does not mutate original)
arr.slice(1, 3);   // [1, 4]
 
// concat: join arrays
[1, 2].concat([3, 4]); // [1, 2, 3, 4]
 
// Remove duplicates
const unique = [...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]

6. Object Operations

Basics

const user = {
  id: 1,
  name: "Alice",
  age: 30,
};
 
// Property access
user.name;         // "Alice"
user["name"];      // "Alice" (dynamic key access)
 
// Add / update / delete
user.email = "alice@example.com";
user.age = 31;
delete user.age;
 
// Check property existence
"name" in user;    // true
user.hasOwnProperty("name"); // true

Object Static Methods

const obj = { a: 1, b: 2, c: 3 };
 
Object.keys(obj);    // ["a", "b", "c"]
Object.values(obj);  // [1, 2, 3]
Object.entries(obj); // [["a", 1], ["b", 2], ["c", 3]]
 
// Convert entries back to object
Object.fromEntries([["a", 1], ["b", 2]]); // { a: 1, b: 2 }
 
// Shallow copy
const copy = Object.assign({}, obj);
const copy2 = { ...obj }; // spread is more readable
 
// Freeze (make immutable)
const frozen = Object.freeze({ x: 1 });
frozen.x = 2; // silently ignored (throws in strict mode)

Shorthand and Method Definitions

const name = "Bob";
const age = 25;
 
// Property shorthand when variable name matches key
const person = { name, age }; // { name: "Bob", age: 25 }
 
// Method shorthand
const obj = {
  greet() {
    return `Hello, ${this.name}`;
  },
  // Arrow functions do not bind their own `this`
};
 
// Computed property names
const key = "color";
const theme = { [key]: "blue" }; // { color: "blue" }

7. Control Flow

if / else

const score = 75;
 
if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}

switch

const status = "loading";
 
switch (status) {
  case "loading":
    console.log("Loading");
    break;
  case "success":
    console.log("Success");
    break;
  case "error":
    console.log("Error");
    break;
  default:
    console.log("Unknown");
}

Loops

// for
for (let i = 0; i < 3; i++) {
  console.log(i); // 0, 1, 2
}
 
// for...of (iterate values of an iterable)
for (const item of ["a", "b", "c"]) {
  console.log(item);
}
 
// for...in (iterate keys of an object — avoid with arrays)
const obj = { a: 1, b: 2 };
for (const key in obj) {
  console.log(key, obj[key]);
}
 
// while
let count = 0;
while (count < 3) {
  count++;
}
 
// break / continue
for (const n of [1, 2, 3, 4, 5]) {
  if (n === 3) continue; // skip
  if (n === 5) break;    // exit loop
  console.log(n); // 1, 2, 4
}

8. Functions

Function Declaration / Expression / Arrow Function

// Function declaration (hoisted)
function add(a, b) {
  return a + b;
}
 
// Function expression (not hoisted)
const multiply = function (a, b) {
  return a * b;
};
 
// Arrow function (concise syntax)
const square = (n) => n * n;
const greet = (name) => `Hello, ${name}`;
const noop = () => {};
 
// Multi-line
const divide = (a, b) => {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
};

Default Arguments / Rest Parameters

// Default arguments
const greet = (name = "Guest") => `Hello, ${name}`;
greet();          // "Hello, Guest"
greet("Alice");   // "Hello, Alice"
 
// Rest parameters
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
sum(1, 2, 3, 4); // 10

Closures

const makeCounter = (initial = 0) => {
  let count = initial;
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count,
  };
};
 
const counter = makeCounter(10);
counter.increment(); // 11
counter.increment(); // 12
counter.getCount();  // 12

Higher-Order Functions

// Accepts a function
const applyTwice = (fn, value) => fn(fn(value));
applyTwice(x => x + 1, 5); // 7
 
// Returns a function
const multiplier = (factor) => (num) => num * factor;
const double = multiplier(2);
double(5); // 10

9. Spread / Rest Syntax

Spread (...)

// Expand arrays
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b]; // [1, 2, 3, 4, 5, 6]
 
// Shallow copy of array
const copy = [...a];
 
// Spread into function arguments
Math.max(...a); // 3
 
// Spread / merge objects
const base = { x: 1, y: 2 };
const extended = { ...base, z: 3 };       // { x: 1, y: 2, z: 3 }
const overridden = { ...base, x: 99 };    // { x: 99, y: 2 } (last wins)

Rest (...)

// Array rest
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]
 
// Object rest
const { name, ...others } = { name: "Alice", age: 30, role: "admin" };
// name = "Alice", others = { age: 30, role: "admin" }
 
// Rest parameters in functions
const logAll = (first, ...rest) => {
  console.log("First:", first);
  console.log("Rest:", rest);
};
logAll(1, 2, 3, 4); // First: 1, Rest: [2, 3, 4]

10. Destructuring

Array Destructuring

const [a, b, c] = [10, 20, 30];
 
// Default values
const [x = 0, y = 0] = [5];   // x = 5, y = 0
 
// Swap variables
let p = 1, q = 2;
[p, q] = [q, p]; // p = 2, q = 1
 
// Skip elements
const [, second, , fourth] = [1, 2, 3, 4];
// second = 2, fourth = 4

Object Destructuring

const user = { id: 1, name: "Alice", age: 30 };
 
const { name, age } = user;
 
// Rename on destructure
const { name: userName, age: userAge } = user;
 
// Default values
const { role = "user", name: n } = user;
// role = "user" (key doesn't exist, so default is used)
 
// Nested object
const { address: { city } } = { address: { city: "Tokyo" } };
 
// Destructuring in function parameters
const greet = ({ name, age = 0 }) => `${name} is ${age} years old`;
greet({ name: "Bob", age: 25 }); // "Bob is 25 years old"

11. Async Processing

Promise

// Create a Promise
const fetchData = (id) =>
  new Promise((resolve, reject) => {
    if (id > 0) {
      resolve({ id, name: "Alice" });
    } else {
      reject(new Error("Invalid ID"));
    }
  });
 
// Promise chain
fetchData(1)
  .then((data) => {
    console.log(data);
    return data.name;
  })
  .then((name) => console.log(name))
  .catch((err) => console.error(err))
  .finally(() => console.log("Done"));
 
// Run Promises in parallel
const [user, posts] = await Promise.all([
  fetchUser(1),
  fetchPosts(1),
]);
 
// Use the first resolved result
const first = await Promise.race([fetchA(), fetchB()]);
 
// Get all results regardless of failure
const results = await Promise.allSettled([fetchA(), fetchB()]);
results.forEach((result) => {
  if (result.status === "fulfilled") console.log(result.value);
  if (result.status === "rejected") console.error(result.reason);
});

async / await

// Basic
const getUser = async (id) => {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
  return res.json();
};
 
// Error handling
const loadUser = async (id) => {
  try {
    const user = await getUser(id);
    console.log(user);
  } catch (err) {
    console.error("Failed to load:", err.message);
  }
};
 
// Parallel processing (sequential awaits are slow)
// Sequential (slow)
const a = await fetchA();
const b = await fetchB();
 
// Parallel (fast)
const [a, b] = await Promise.all([fetchA(), fetchB()]);

12. Error Handling

try / catch / finally

try {
  const data = JSON.parse("invalid json");
} catch (err) {
  if (err instanceof SyntaxError) {
    console.error("JSON parse error:", err.message);
  } else {
    throw err; // re-throw unexpected errors
  }
} finally {
  console.log("Always runs");
}

Custom Errors

class AppError extends Error {
  constructor(message, public code) {
    super(message);
    this.name = "AppError";
  }
}
 
const validate = (value) => {
  if (!value) throw new AppError("Value is empty", "EMPTY_VALUE");
};
 
try {
  validate("");
} catch (err) {
  if (err instanceof AppError) {
    console.error(`[${err.code}] ${err.message}`);
  }
}

Error Types

ErrorCommon Cause
SyntaxErrorSyntax error (e.g. JSON.parse)
TypeErrorType mismatch (e.g. null.property)
ReferenceErrorAccessing an undefined variable
RangeErrorOut-of-range value (e.g. new Array(-1))
URIErrorInvalid URI encoding/decoding

13. Classes

Basic Syntax

class Animal {
  // Fields
  #name; // private field
  species = "Unknown"; // public field
 
  constructor(name) {
    this.#name = name;
  }
 
  // Getter
  get name() {
    return this.#name;
  }
 
  // Method
  speak() {
    return `${this.#name} makes a sound`;
  }
 
  // Static method
  static create(name) {
    return new Animal(name);
  }
}
 
const dog = new Animal("Rex");
dog.name;       // "Rex"
dog.speak();    // "Rex makes a sound"
Animal.create("Kitty"); // same as new Animal("Kitty")

Inheritance

class Dog extends Animal {
  #breed;
 
  constructor(name, breed) {
    super(name); // call parent constructor
    this.#breed = breed;
  }
 
  speak() {
    return `${super.speak()} (Woof!)`;
  }
 
  get info() {
    return `${this.name} / ${this.#breed}`;
  }
}
 
const rex = new Dog("Rex", "Shiba Inu");
rex.speak();  // "Rex makes a sound (Woof!)"
rex.info;     // "Rex / Shiba Inu"
rex instanceof Dog;   // true
rex instanceof Animal; // true

14. Modules

Export

// Named export (multiple allowed)
export const PI = 3.14159;
export const add = (a, b) => a + b;
export class Calculator { /* ... */ }
 
// Export together
const subtract = (a, b) => a - b;
const divide = (a, b) => a / b;
export { subtract, divide };
 
// Export with alias
export { subtract as sub };
 
// Default export (one per file)
export default function main() { /* ... */ }

Import

// Named import
import { PI, add } from "./math.js";
 
// Import with alias
import { add as sum } from "./math.js";
 
// Default import
import main from "./main.js";
 
// Import everything as namespace
import * as math from "./math.js";
math.add(1, 2);
 
// Default and named together
import main, { PI, add } from "./module.js";
 
// Side-effects only (just execute)
import "./setup.js";

Dynamic Import

// Lazy load asynchronously
const loadModule = async () => {
  const { add } = await import("./math.js");
  return add(1, 2);
};
 
// Conditional import
if (needsFeature) {
  const { feature } = await import("./feature.js");
  feature();
}

15. Useful Methods

Numbers

Math.floor(4.7);    // 4 (round down)
Math.ceil(4.1);     // 5 (round up)
Math.round(4.5);    // 5 (round to nearest)
Math.abs(-5);       // 5 (absolute value)
Math.max(1, 2, 3);  // 3
Math.min(1, 2, 3);  // 1
Math.pow(2, 10);    // 1024 (exponent)
Math.sqrt(9);       // 3 (square root)
Math.random();      // random number in [0, 1)
 
// Random integer (0–9)
Math.floor(Math.random() * 10);
 
// Round to decimal places
(3.14159).toFixed(2); // "3.14" (returns a string)
Number((3.14159).toFixed(2)); // 3.14 (back to number)
 
// Number checks
Number.isInteger(3);      // true
Number.isFinite(Infinity); // false
Number.isNaN(NaN);        // true (safer than global isNaN)

Array Utilities

// Create a range array
Array.from({ length: 5 }, (_, i) => i);    // [0, 1, 2, 3, 4]
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
 
// Array from string
Array.from("hello"); // ["h", "e", "l", "l", "o"]
 
// Array from Set
Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
 
// Chunk an array
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size)
  );
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

Map / Set

// Map (keys can be any value)
const map = new Map();
map.set("key", "value");
map.set(1, "one");
map.get("key");     // "value"
map.has("key");     // true
map.delete("key");
map.size;           // 1
 
for (const [key, value] of map) {
  console.log(key, value);
}
 
// Set (unique collection)
const set = new Set([1, 2, 3, 2, 1]);
set.size;           // 3
set.add(4);
set.has(2);         // true
set.delete(2);
 
for (const value of set) {
  console.log(value);
}

JSON

// Object → JSON string
const json = JSON.stringify({ name: "Alice", age: 30 });
// '{"name":"Alice","age":30}'
 
// Pretty print
JSON.stringify({ name: "Alice" }, null, 2);
/*
{
  "name": "Alice"
}
*/
 
// JSON string → Object
const obj = JSON.parse('{"name":"Alice","age":30}');
// { name: "Alice", age: 30 }
 
// Deep copy (simple)
const deepCopy = JSON.parse(JSON.stringify(original));
// Note: undefined, Function, Symbol are lost

Date

const now = new Date();
 
now.getFullYear();  // year (e.g. 2026)
now.getMonth();     // month - 1 (0–11) ← watch out
now.getDate();      // day of month
now.getDay();       // day of week (0=Sun, 6=Sat)
now.getHours();     // hours
now.getMinutes();   // minutes
now.getSeconds();   // seconds
now.getTime();      // milliseconds since epoch
 
// Create a date
new Date(2026, 0, 1);   // Jan 1, 2026 (month is 0-indexed)
new Date("2026-01-01"); // ISO 8601 format
 
// Format
now.toISOString();               // "2026-01-01T00:00:00.000Z"
now.toLocaleDateString("en-US"); // "1/1/2026"
now.toLocaleString("en-US");     // "1/1/2026, 12:00:00 AM"

Tips

Falsy Values

// The following values are treated as false in if statements
if (false)     { /* not executed */ }
if (0)         { /* not executed */ }
if (-0)        { /* not executed */ }
if (0n)        { /* not executed */ }
if ("")        { /* not executed */ }
if (null)      { /* not executed */ }
if (undefined) { /* not executed */ }
if (NaN)       { /* not executed */ }
 
// [] and {} are truthy — watch out
if ([]) { /* executed */ }
if ({}) { /* executed */ }

Immutable Data Operations

const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };
 
// Methods that mutate the original array
arr.sort();
arr.splice(0, 1);
arr.push(4);
 
// Use methods that return a new array instead
const sorted = [...arr].sort();
const removed = arr.filter((_, i) => i !== 0);
const added = [...arr, 4];
 
// Same for objects — use spread to copy
const updated = { ...obj, a: 99 };
const deleted = Object.fromEntries(
  Object.entries(obj).filter(([k]) => k !== "a")
);

Short-Circuit Evaluation Patterns

// Default value for objects
const config = userConfig ?? {};
 
// Safe function call
callback?.();
 
// Conditional execution
isAdmin && showAdminPanel();
 
// Merge with defaults
const options = { ...defaultOptions, ...userOptions };