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!
- Variables & Data Types
- Operators
- Control Flow
- Functions
- Arrays
- Objects
- Strings
- ES6+ Features
- DOM Manipulation
- Events
- Asynchronous JavaScript
- Error Handling
- Classes & OOP
- Modules
- Built-in Methods
- Browser APIs
- Tips & Best Practices
// 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;// 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;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]"// 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" // truelet 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)// 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// 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)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)let result = condition ? valueIfTrue : valueIfFalse;
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
}switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}// 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 - 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
}// 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" });// 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;
}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}`));(function() {
console.log("I run immediately!");
})();
// With arrow function
(() => {
console.log("I also run immediately!");
})();function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3const 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]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 portionconst 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?)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]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]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]// 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);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"); // trueconst 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
});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: "john@email.com" } };
const { info: { name, email } } = user;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"
};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"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"// 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']// 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
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}// 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 promiseclass 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}`;
}
}// 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)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">// 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);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// 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// 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"// 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);
}
});// 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);
});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
});
});
});// 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);
});
});// 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);
})();// 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 codetry {
// 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");
}class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
this.code = 400;
}
}
throw new ValidationError("Invalid input");// 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);
});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";
}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.`;
}
}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");
}
}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);
}
}// 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 };// 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";// Exporting
module.exports = { add, subtract };
exports.multiply = (a, b) => a * b;
// Importing
const math = require("./math");
const { add, multiply } = require("./math");// 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// 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// 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);// 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"));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);
}// 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
});// 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);// 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;// 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)// 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// 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);