Skip to content

JavaScript Complete Reference

Mattscreative edited this page Feb 21, 2026 · 1 revision

JavaScript Complete Reference Guide

Table of Contents


Variables and Data Types

Variable Declaration

// let - block scoped, can be reassigned
let x = 5;
x = 10;  // OK

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

// var - function scoped (avoid)
var oldWay = "deprecated";

Data Types

// Primitive Types
let str = "Hello";           // String
let num = 42;               // Number
let big = 9007199254740991n; // BigInt
let bool = true;            // Boolean
let nothing = null;         // Null
let notDefined;             // Undefined
let sym = Symbol("id");    // Symbol

// Reference Types
let arr = [];               // Array
let obj = {};               // Object
let func = function(){};   // Function

Operators

Arithmetic

+   // Addition
-   // Subtraction
*   // Multiplication
/   // Division
%   // Modulo (remainder)
**  // Exponentiation
++  // Increment
--  // Decrement

Assignment

=   // Assignment
+=  // Addition assignment
-=  // Subtraction assignment
*=  // Multiplication assignment
/=  // Division assignment
%=  // Modulo assignment
**= // Exponentiation assignment

Comparison

==   // Loose equality (type coercion)
===  // Strict equality (no coercion)
!=   // Loose inequality
!==  // Strict inequality
>    // Greater than
<    // Less than
>=   // Greater than or equal
<=   // Less than or equal

Logical

&&  // AND
||  // OR
!   // NOT
??  // Nullish coalescing
?.  // Optional chaining

Control Flow

If/Else

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

// Ternary operator
const result = condition ? valueIfTrue : valueIfFalse;

Switch

switch (value) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

Loops

// for
for (let i = 0; i < 10; i++) { }

// for...of (arrays)
for (const item of array) { }

// for...in (objects)
for (const key in object) { }

// while
while (condition) { }

// do...while
do { } while (condition);

Functions

Declaration

function name(params) {
    return value;
}

// Arrow function
const name = (params) => value;

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

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

Methods

// call
func.call(thisArg, arg1, arg2);

// apply
func.apply(thisArg, [args]);

// bind
const bound = func.bind(thisArg);

Arrays

Creation

const arr = [1, 2, 3];
const arr2 = new Array(1, 2, 3);
const empty = [];

Methods

// Adding/removing
push(item);     // Add to end
pop();          // Remove from end
unshift(item);  // Add to beginning
shift();        // Remove from beginning

// Searching
indexOf(item);      // First index
includes(item);     // Boolean
find(fn);          // First match
findIndex(fn);     // Index of first match

// Transforming
map(fn);           // Transform each element
filter(fn);        // Filter elements
reduce(fn, init);  // Reduce to single value
flatMap(fn);       // Map then flatten
slice(start, end); // Copy portion
splice(start, deleteCount, items); // Add/remove

// Sorting
sort(fn);          // Sort in place
reverse();         // Reverse in place

// Other
concat(arr);       // Combine arrays
join(separator);   // Join as string
forEach(fn);       // Iterate
some(fn);          // Any match?
every(fn);         // All match?
flat(depth);       // Flatten array

Objects

Creation

const obj = { key: "value" };
const obj2 = new Object();

Methods

Object.keys(obj);      // Array of keys
Object.values(obj);    // Array of values
Object.entries(obj);   // Array of [key, value]
Object.assign(target, source); // Copy properties
Object.freeze(obj);    // Prevent changes
Object.seal(obj);      // Prevent add/remove

// Destructuring
const { a, b } = obj;
const { a: newA } = obj;  // Rename
const { a, ...rest } = obj; // Rest

Classes

Declaration

class ClassName {
    constructor(params) {
        this.property = params;
    }
    
    method() { }
    
    static staticMethod() { }
    
    get prop() { }
    set prop(value) { }
}

Inheritance

class Child extends Parent {
    constructor(params) {
        super(params);
    }
    
    method() {
        super.method();
    }
}

Async JavaScript

Promises

const promise = new Promise((resolve, reject) => { });

promise
    .then(onFulfilled)
    .catch(onRejected)
    .finally(onSettled);

Promise.all([p1, p2]);
Promise.race([p1, p2]);
Promise.allSettled([p1, p2]);
Promise.resolve(value);
Promise.reject(error);

Async/Await

async function name() {
    try {
        const data = await promise;
        return data;
    } catch (error) {
        console.error(error);
    }
}

Fetch

fetch(url, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
})
    .then(r => r.json())
    .catch(e => console.error(e));

DOM Manipulation

Selection

document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('.class');
element.children;
element.parentElement;

Content

element.textContent = "text";
element.innerHTML = "<p>HTML</p>";
element.getAttribute('attr');
element.setAttribute('attr', 'value');
element.dataset.name = "value";

Styles

element.style.color = "red";
element.classList.add('class');
element.classList.remove('class');
element.classList.toggle('class');
element.classList.contains('class');
getComputedStyle(element);

Events

element.addEventListener('click', handler);
element.removeEventListener('click', handler);
element.addEventListener('click', handler, { once: true });

DOM Creation

document.createElement('div');
parent.appendChild(child);
parent.removeChild(child);
element.cloneNode(true);
element.remove();

String Methods

str.length;
str.charAt(index);
str.slice(start, end);
str.substring(start, end);
str.split(separator);
str.toUpperCase();
str.toLowerCase();
str.trim();
str.includes(substr);
str.startsWith(substr);
str.endsWith(substr);
str.replace(search, replace);
str.match(regex);
str.indexOf(substr);
str.lastIndexOf(substr);
str.concat(str2);
str.repeat(n);
str.padStart(len, pad);
str.padEnd(len, pad);
str.includes(substr);
str.search(regex);

Number and Math

Number

Number(value);
parseInt(str, radix);
parseFloat(str);
Number.isNaN(value);
Number.isFinite(value);
Number.isInteger(value);
Number.isSafeInteger(value);

num.toFixed(digits);
num.toPrecision(digits);
num.toString(radix);

Math

Math.abs(x);
Math.round(x);
Math.floor(x);
Math.ceil(x);
Math.trunc(x);
Math.max(...nums);
Math.min(...nums);
Math.pow(x, y);
Math.sqrt(x);
Math.random();
Math.sin(x);
Math.cos(x);
Math.tan(x);
Math.PI;
Math.E;

JSON

JSON.stringify(obj, replacer, space);
JSON.parse(str, reviver);

Utility Functions

// Type checking
typeof value;  // "string", "number", "boolean", "object", "function", "undefined"

Array.isArray(arr);
value instanceof Constructor;

// Value checking
value === null;
value === undefined;

// Cloning
[...arr];           // Shallow copy array
{ ...obj };         // Shallow copy object
JSON.parse(JSON.stringify(obj)); // Deep clone (simple)

 // Random
Math.random();              // 0-1
Math.floor(Math.random() * max);  // 0 to max-1

ES6+ Features

// Arrow functions
const fn = () => { };
const fn = x => x * 2;

// Template literals
const str = `Hello, ${name}`;

// Destructuring
const [a, b] = array;
const { x, y } = object;

// Spread
const newArr = [...arr1, ...arr2];
const newObj = { ...obj1, ...obj2 };

// Classes
class Name { }

// Modules
export const name = value;
export default function() { }
import { name } from './module';
import name from './module';

// Promises
const promise = new Promise((resolve, reject) => { });

// Async/await
async function fn() { await promise; }

// Optional chaining
obj?.prop?.nested;
arr?.[0];
fn?.();

// Nullish coalescing
const value = null ?? "default";

// BigInt
const big = 9007199254740991n;

// Dynamic import
const module = await import('./module.js');

Error Handling

try {
    // code
} catch (error) {
    console.error(error.message);
} finally {
    // cleanup
}

throw new Error("message");
throw new TypeError("message");
throw new CustomError("message");

// Async error handling
try {
    await promise;
} catch (error) {
    console.error(error);
}

Common Patterns

Debounce

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

Throttle

function throttle(fn, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            fn.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

Memoize

function memoize(fn) {
    const cache = new Map();
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        const result = fn.apply(this, args);
        cache.set(key, result);
        return result;
    };
}

Browser APIs

// Local Storage
localStorage.setItem('key', 'value');
localStorage.getItem('key');
localStorage.removeItem('key');

// Session Storage
sessionStorage.setItem('key', 'value');

// Timer
setTimeout(fn, ms);
setInterval(fn, ms);
clearTimeout(id);
clearInterval(id);

// Location
window.location.href;
window.location.reload();

// Console
console.log();
console.error();
console.warn();
console.table();
console.time();
console.timeEnd();
console.trace();

Clone this wiki locally