JavaScript
🚀 JavaScript Complete Cheat Sheet
From Beginner to Advanced
J AVA S C R I P T
ES6+
LICENSE MIT
A comprehensive guide to mastering JavaScript ✨
📑 Table of Contents
🎯 JavaScript Basics
🔀 Control Flow
⚡ Functions
📦 Arrays
🏗️ Objects
🌐 DOM Manipulation
✨ ES6+ Features
⏳ Asynchronous JavaScript
🛡️ Error Handling
🎨 Object-Oriented Programming
🚀 Advanced Concepts
📚 Quick Reference
🎯 JavaScript Basics
📝 Variables
Variables are containers for storing data values. JavaScript has three ways to declare variables:
// var - Function scoped, can be redeclared (older way)
var name = "John";
// let - Block scoped, can be reassigned (modern way)
let age = 25;
// const - Block scoped, cannot be reassigned (for constants)
const PI = 3.14159;
Variable Comparison
Keyword Scope Redeclare Reassign Hoisted
var Function ✅ Yes ✅ Yes ✅ Yes (undefined)
let Block ❌ No ✅ Yes ❌ No (TDZ)
const Block ❌ No ❌ No ❌ No (TDZ)
💡 Best Practice: Use const by default, let when reassignment is needed, avoid var .
📊 Data Types
JavaScript has 8 data types divided into Primitive and Non-Primitive:
Primitive Types (Immutable)
// 1. String - Text data
let greeting = "Hello World";
let name = "JavaScript";
let template = `Hello ${name}`; // Template literal
// 2. Number - Integers and decimals
let integer = 42;
let decimal = 3.14;
let negative = -10;
let infinity = Infinity;
let notANumber = NaN;
// 3. BigInt - Large integers
let bigNumber = 9007199254740991n;
// 4. Boolean - true or false
let isActive = true;
let isLoggedIn = false;
// 5. Undefined - Variable declared but not assigned
let notAssigned;
[Link](notAssigned); // undefined
// 6. Null - Intentional absence of value
let emptyValue = null;
// 7. Symbol - Unique identifier
let id = Symbol("id");
let anotherId = Symbol("id");
[Link](id === anotherId); // false (always unique)
Non-Primitive Types (Reference)
// Object - Collection of key-value pairs
let person = {
name: "John",
age: 30,
isStudent: false,
};
// Array - Ordered list of values
let colors = ["red", "green", "blue"];
// Function - Reusable code block
function greet(name) {
return `Hello, ${name}!`;
}
Type Checking
typeof "Hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (known bug)
typeof {}; // "object"
typeof []; // "object"
typeof function () {}; // "function"
typeof Symbol("x"); // "symbol"
typeof 10n; // "bigint"
// Better array check
[Link]([1, 2, 3]); // true
[Link]({}); // false
➕ Operators
Arithmetic Operators
let a = 10,
b = 3;
a + b; // 13 (Addition)
a - b; // 7 (Subtraction)
a * b; // 30 (Multiplication)
a / b; // 3.33 (Division)
a % b; // 1 (Modulus/Remainder)
a ** b; // 1000 (Exponentiation)
// Increment/Decrement
let x = 5;
x++; // 5, then x = 6 (Post-increment)
++x; // 7 (Pre-increment)
x--; // 7, then x = 6 (Post-decrement)
--x; // 5 (Pre-decrement)
Assignment Operators
let x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
x **= 3; // x = x ** 3 → 8
Comparison Operators
// Equality (with type coercion)
5 == "5"; // true
5 != "6"; // true
// Strict Equality (no type coercion) ⭐ Recommended
5 === "5"; // false
5 !== "6"; // true
// Relational
5 > 3; // true
5 < 3; // false
5 >= 5; // true
5 <= 4; // false
⚠️ Always use === and !== to avoid unexpected type coercion!
Logical Operators
// AND - Both must be true
true && true; // true
true && false; // false
// OR - At least one must be true
true || false; // true
false || false; // false
// NOT - Inverts boolean
!true; // false
!false; // true
// Practical Examples
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
[Link]("Can drive");
}
// Short-circuit evaluation
let name = null;
let displayName = name || "Guest"; // "Guest"
// Nullish coalescing (ES2020)
let value = null ?? "default"; // "default"
let zero = 0 ?? "default"; // 0 (only null/undefined trigger default)
Ternary Operator
// Syntax: condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
[Link](status); // "Adult"
// Nested ternary (use sparingly)
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
🔀 Control Flow
Conditional Statements
if...else Statement
let temperature = 25;
🔥
if (temperature > 30) {
[Link]("It's hot! ");
☀️
} else if (temperature > 20) {
[Link]("It's warm! ");
🌤️
} else if (temperature > 10) {
[Link]("It's cool! ");
[Link]("It's cold! ❄️");
} else {
switch Statement
let day = "Monday";
switch (day) {
💼");
case "Monday":
[Link]("Start of work week
break;
🎉");
case "Friday":
[Link]("TGIF!
break;
case "Saturday":
🎮");
case "Sunday":
[Link]("Weekend!
break;
📅");
default:
[Link]("Regular day
}
💡 Remember: Always include break to prevent fall-through!
🔄 Loops
for Loop
// Basic for loop
for (let i = 0; i < 5; i++) {
[Link](`Iteration: ${i}`);
}
// Output: 0, 1, 2, 3, 4
🍎 🍌 🍊
// Looping through array
let fruits = [" ", " ", " "];
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
while Loop
// Executes while condition is true
let count = 0;
while (count < 3) {
[Link](`Count: ${count}`);
count++;
}
do...while Loop
// Executes at least once, then checks condition
let num = 0;
do {
[Link](`Number: ${num}`);
num++;
} while (num < 3);
for...of Loop (ES6)
// Iterates over iterable values (arrays, strings, etc.)
let colors = ["red", "green", "blue"];
for (let color of colors) {
[Link](color);
}
// With strings
for (let char of "Hello") {
[Link](char); // H, e, l, l, o
}
for...in Loop
// Iterates over object keys
let person = { name: "John", age: 30, city: "NYC" };
for (let key in person) {
[Link](`${key}: ${person[key]}`);
}
// name: John, age: 30, city: NYC
Loop Control
// break - Exit loop immediately
for (let i = 0; i < 10; i++) {
if (i === 5) break;
[Link](i);
}
// Output: 0, 1, 2, 3, 4
// continue - Skip current iteration
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
[Link](i);
}
// Output: 0, 1, 3, 4
⚡ Functions
Function Declaration
// Named function - Hoisted
function greet(name) {
return `Hello, ${name}!`;
}
[Link](greet("World")); // "Hello, World!"
// With default parameters
function greetUser(name = "Guest") {
return `Hello, ${name}!`;
}
greetUser(); // "Hello, Guest!"
greetUser("Bob"); // "Hello, Bob!"
Function Expression
// Anonymous function assigned to variable - Not hoisted
const add = function (a, b) {
return a + b;
};
[Link](add(5, 3)); // 8
Arrow Functions (ES6)
// Basic syntax
const multiply = (a, b) => {
return a * b;
};
// Single expression - Implicit return
const multiplyShort = (a, b) => a * b;
// Single parameter - Parentheses optional
const square = (x) => x * x;
// No parameters
const sayHello = () => "Hello!";
// Returning objects (wrap in parentheses)
const createUser = (name, age) => ({ name, age });
Regular vs Arrow Functions
Feature Regular Function Arrow Function
this binding Dynamic Lexical (inherits)
arguments object ✅ Available ❌ Not available
Constructor ✅ Can use new ❌ Cannot use new
Hoisting ✅ Yes ❌ No
IIFE (Immediately Invoked Function Expression)
// Executes immediately after creation
(function () {
[Link]("Runs immediately!");
})();
// With arrow function
(() => {
[Link]("Arrow IIFE!");
})();
// Useful for creating private scope
const counter = (function () {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count,
};
})();
[Link](); // 1
[Link](); // 2
[Link](); // 2
Rest Parameters & Spread Operator
// Rest Parameters - Collect multiple arguments
function sum( ... numbers) {
return [Link]((total, num) => total + num, 0);
}
sum(1, 2, 3, 4); // 10
// Spread Operator - Expand arrays/objects
const arr1 = [1, 2, 3];
const arr2 = [ ... arr1, 4, 5]; // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ... obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
📦 Arrays
Creating Arrays
// Array literal (recommended)
let fruits = ["apple", "banana", "orange"];
// Array constructor
let numbers = new Array(1, 2, 3);
// [Link]()
[Link]("Hello"); // ["H", "e", "l", "l", "o"]
[Link]({ length: 5 }); // [undefined x 5]
// [Link]()
[Link](1, 2, 3); // [1, 2, 3]
Accessing Elements
let arr = ["a", "b", "c", "d", "e"];
arr[0]; // "a" (first)
arr[4]; // "e" (last by index)
[Link](-1); // "e" (last - ES2022)
[Link](-2); // "d" (second last)
[Link]; // 5
Mutating Methods (Modify Original Array)
let arr = [1, 2, 3];
// Add/Remove from end
[Link](4); // [1, 2, 3, 4] - Returns new length
[Link](); // [1, 2, 3] - Returns removed element
// Add/Remove from beginning
[Link](0); // [0, 1, 2, 3] - Returns new length
[Link](); // [1, 2, 3] - Returns removed element
// Splice - Add/Remove anywhere
[Link](1, 1); // Removes 1 element at index 1 → [1, 3]
[Link](1, 0, 2); // Inserts 2 at index 1 → [1, 2, 3]
[Link](1, 1, 5); // Replace → [1, 5, 3]
// Others
[Link](); // Reverses in place
[Link](); // Sorts in place
[Link](0); // Fills all with 0
Non-Mutating Methods (Return New Array)
let arr = [1, 2, 3, 4, 5];
// Slice - Extract portion
[Link](1, 3); // [2, 3] (start inclusive, end exclusive)
[Link](-2); // [4, 5] (last 2 elements)
// Concat - Merge arrays
[Link]([6, 7]); // [1, 2, 3, 4, 5, 6, 7]
// Join - Convert to string
[Link]("-"); // "1-2-3-4-5"
// Includes - Check existence
[Link](3); // true
// Find index
[Link](3); // 2
[Link](3); // 2
Iteration Methods
let numbers = [1, 2, 3, 4, 5];
// forEach - Execute for each element
[Link]((num, index) => {
[Link](`${index}: ${num}`);
});
// map - Transform elements
let doubled = [Link]((num) => num * 2);
// [2, 4, 6, 8, 10]
// filter - Filter elements
let evens = [Link]((num) => num % 2 === 0);
// [2, 4]
// reduce - Reduce to single value
let sum = [Link]((acc, num) => acc + num, 0);
// 15
// find - Find first match
let found = [Link]((num) => num > 3);
// 4
// findIndex - Find index of first match
let index = [Link]((num) => num > 3);
// 3
// some - Test if any element passes
let hasEven = [Link]((num) => num % 2 === 0);
// true
// every - Test if all elements pass
let allPositive = [Link]((num) => num > 0);
// true
// flat - Flatten nested arrays
[
[1, 2],
[3, 4],
].flat(); // [1, 2, 3, 4]
// flatMap - Map + flatten
[1, 2].flatMap((x) => [x, x * 2]); // [1, 2, 2, 4]
Array Destructuring
let [a, b, c] = [1, 2, 3];
[Link](a, b, c); // 1 2 3
// Skip elements
let [first, , third] = [1, 2, 3];
// Rest pattern
let [head, ... tail] = [1, 2, 3, 4];
[Link](head); // 1
[Link](tail); // [2, 3, 4]
// Default values
let [x = 10, y = 20] = [5];
[Link](x, y); // 5 20
// Swap variables
let m = 1,
n = 2;
[m, n] = [n, m]; // m = 2, n = 1
🏗️ Objects
Creating Objects
// Object literal
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
hobbies: ["reading", "gaming"],
address: {
city: "New York",
country: "USA",
},
// Method
fullName() {
return `${[Link]} ${[Link]}`;
},
};
// Accessing properties
[Link]; // "John" (dot notation)
person["lastName"]; // "Doe" (bracket notation)
[Link]; // "New York" (nested)
[Link](); // "John Doe" (method)
Object Methods
const obj = { a: 1, b: 2, c: 3 };
// Keys, Values, Entries
[Link](obj); // ["a", "b", "c"]
[Link](obj); // [1, 2, 3]
[Link](obj); // [["a", 1], ["b", 2], ["c", 3]]
// fromEntries - Convert entries back to object
[Link]([
["a", 1],
["b", 2],
]); // { a: 1, b: 2 }
// Assign - Copy/merge objects
[Link]({}, obj, { d: 4 }); // { a: 1, b: 2, c: 3, d: 4 }
// Freeze - Make immutable
[Link](obj);
obj.a = 10; // Silently fails
// Seal - Prevent adding/removing properties
[Link](obj);
// Check property existence
"a" in obj; // true
[Link]("a"); // true
Object Destructuring
const user = {
name: "Alice",
age: 25,
email: "alice@[Link]",
};
// Basic destructuring
const { name, age } = user;
[Link](name, age); // "Alice" 25
// Rename variables
const { name: userName, age: userAge } = user;
// Default values
const { name: n, country = "Unknown" } = user;
// Nested destructuring
const data = {
user: { name: "Bob", profile: { avatar: "[Link]" } },
};
const {
user: {
profile: { avatar },
},
} = data;
// Rest pattern
const { name: userName2, ... rest } = user;
// rest = { age: 25, email: "alice@[Link]" }
The this Keyword
// In object methods - refers to the object
const person = {
name: "John",
greet() {
[Link](`Hello, I'm ${[Link]}`);
},
};
[Link](); // "Hello, I'm John"
// Arrow functions don't have their own this
const obj = {
name: "Object",
regularFunc() {
[Link]([Link]); // "Object"
},
arrowFunc: () => {
[Link]([Link]); // undefined (inherits from parent scope)
},
};
// Binding this
function greet() {
[Link](`Hello, ${[Link]}`);
}
const userObj = { name: "Alice" };
[Link](userObj); // "Hello, Alice"
[Link](userObj); // "Hello, Alice"
const boundGreet = [Link](userObj);
boundGreet(); // "Hello, Alice"
🌐 DOM Manipulation
Selecting Elements
// Single element selectors
[Link]("myId");
[Link](".myClass"); // First match
[Link]("#id .class"); // CSS selector
// Multiple elements selectors
[Link]("myClass");
[Link]("div");
[Link](".myClass"); // All matches
// Convert NodeList to Array
const elements = [ ... [Link]("div")];
Creating & Modifying Elements
// Create element
const div = [Link]("div");
[Link] = "newDiv";
[Link] = "container";
[Link] = "Hello World";
[Link] = "<strong>Bold text</strong>";
// Add attributes
[Link]("data-id", "123");
[Link]("data-id"); // "123"
[Link]("data-id");
[Link]("data-id"); // false
// Classes
[Link]("active", "visible");
[Link]("visible");
[Link]("active");
[Link]("active"); // true/false
[Link]("old", "new");
// Styles
[Link] = "red";
[Link] = "blue";
[Link] = "color: red; background: blue;";
DOM Traversal
const element = [Link]("#myElement");
// Parent
[Link];
[Link];
[Link](".ancestor");
// Children
[Link];
[Link];
[Link];
[Link];
// Siblings
[Link];
[Link];
Adding/Removing Elements
const parent = [Link]("#parent");
const child = [Link]("div");
// Append
[Link](child);
[Link](child, "text");
[Link](child);
// Insert relative to element
[Link](newChild, referenceChild);
[Link]("beforebegin", "<div>Before</div>");
[Link]("afterend", "<div>After</div>");
// Remove
[Link]();
[Link](child);
// Replace
[Link](newChild, oldChild);
[Link](newChild);
// Clone
[Link](false); // Shallow
[Link](true); // Deep
Event Handling
const button = [Link]("#myButton");
// addEventListener (recommended)
[Link]("click", function (event) {
[Link]("Clicked!", [Link]);
});
// Arrow function
[Link]("click", (e) => {
[Link]("Clicked!");
});
// Named function (for removal)
function handleClick(e) {
[Link]("Clicked!");
}
[Link]("click", handleClick);
[Link]("click", handleClick);
// Event options
[Link]("click", handler, {
once: true, // Remove after first trigger
capture: true, // Capture phase
passive: true, // Won't call preventDefault()
});
Common Events
// Mouse events
[Link]("click", handler);
[Link]("dblclick", handler);
[Link]("mouseenter", handler);
[Link]("mouseleave", handler);
// Keyboard events
[Link]("keydown", (e) => {
[Link]([Link], [Link], [Link]);
});
// Form events
[Link]("submit", (e) => {
[Link]();
});
[Link]("input", handler);
[Link]("change", handler);
[Link]("focus", handler);
[Link]("blur", handler);
// Window events
[Link]("load", handler);
[Link]("resize", handler);
[Link]("scroll", handler);
[Link]("DOMContentLoaded", handler);
Event Delegation
// Add one listener to parent instead of each child
[Link]("#todo-list").addEventListener("click", (e) => {
if ([Link](".delete-btn")) {
[Link]("li").remove();
}
if ([Link](".edit-btn")) {
// Handle edit
}
});
✨ ES6+ Features
Template Literals
const name = "World";
const age = 25;
// String interpolation
const greeting = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div class="card">
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
// Expressions
[Link](`Sum: ${2 + 2}`);
[Link](`Status: ${age >= 18 ? "Adult" : "Minor"}`);
Optional Chaining (?.)
const user = {
name: "John",
address: {
city: "NYC",
},
};
// Old way (verbose)
const city = user && [Link] && [Link];
// Optional chaining
const cityNew = user?.address?.city; // "NYC"
const zip = user?.address?.zip; // undefined (no error)
// With arrays and functions
const first = arr?.[0];
const result = obj?.method?.();
// Nullish coalescing combo
const cityOrDefault = user?.address?.city ?? "Unknown";
Nullish Coalescing (??)
// Only triggers for null/undefined (not 0, "", false)
const value1 = null ?? "default"; // "default"
const value2 = undefined ?? "default"; // "default"
const value3 = 0 ?? "default"; // 0
const value4 = "" ?? "default"; // ""
const value5 = false ?? "default"; // false
// Comparison with ||
const orValue = 0 || "default"; // "default" (0 is falsy)
const nullValue = 0 ?? "default"; // 0 (only null/undefined)
Map & Set
// Map - Key-value pairs with any key type
const map = new Map();
[Link]("name", "John");
[Link](1, "one");
[Link]({}, "object key");
[Link]("name"); // "John"
[Link]("name"); // true
[Link]; // 3
[Link]("name");
[Link]();
// Iterate Map
for (const [key, value] of map) {
[Link](key, value);
}
// Set - Unique values only
const set = new Set([1, 2, 3, 3, 4]);
[Link](set); // Set {1, 2, 3, 4}
[Link](5);
[Link](3); // true
[Link](3);
[Link]; // 4
// Convert array to unique values
const unique = [ ... new Set([1, 1, 2, 2, 3])]; // [1, 2, 3]
⏳ Asynchronous JavaScript
Callbacks
// Basic callback pattern
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 1000);
}
fetchData((data) => {
[Link](data); // After 1 second: "Data received!"
});
Promises
// Creating a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
✅
if (success) {
resolve("Success! ");
❌");
} else {
reject("Error!
}
}, 1000);
});
// Consuming a Promise
promise
.then((result) => {
[Link](result);
return "Next value";
})
.then((value) => {
[Link](value);
})
.catch((error) => {
[Link](error);
})
.finally(() => {
[Link]("Always runs");
});
Promise Methods
const p1 = [Link](1);
const p2 = [Link](2);
const p3 = [Link](3);
// [Link] - Wait for all to resolve
[Link]([p1, p2, p3]).then(([r1, r2, r3]) => [Link](r1, r2, r3));
// [Link] - Wait for all, regardless of outcome
[Link]([p1, [Link]("Error")]).then((results) =>
[Link](results)
);
// [Link] - First to settle wins
[Link]([p1, p2, p3]).then((first) => [Link](first));
// [Link] - First to resolve wins
[Link]([[Link](1), p2, p3]).then((first) =>
[Link](first));
Async/Await
// Async function always returns a Promise
async function fetchUserData() {
const response = await fetch("/api/user");
const data = await [Link]();
return data;
}
// Error handling with try/catch
async function fetchData() {
try {
const response = await fetch("/api/data");
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
const data = await [Link]();
return data;
} catch (error) {
[Link]("Fetch error:", error);
throw error;
} finally {
[Link]("Fetch completed");
}
}
Parallel vs Sequential
// Sequential - One after another (slower)
async function sequential() {
const user = await fetchUser();
const posts = await fetchPosts();
return { user, posts };
}
// Parallel - All at once (faster)
async function parallel() {
const [user, posts] = await [Link]([fetchUser(), fetchPosts()]);
return { user, posts };
}
Fetch API
// GET request
async function getData() {
const response = await fetch("[Link]
const data = await [Link]();
return data;
}
// POST request
async function postData(data) {
const response = await fetch("[Link] {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer token123",
},
body: [Link](data),
});
return [Link]();
}
🛡️ Error Handling
Try...Catch...Finally
try {
const result = riskyOperation();
[Link](result);
} catch (error) {
[Link]("Error:", [Link]);
[Link]("Stack:", [Link]);
} finally {
cleanup();
}
// Catch specific error types
try {
[Link]("invalid json");
} catch (error) {
if (error instanceof SyntaxError) {
[Link]("Invalid JSON syntax");
} else if (error instanceof TypeError) {
[Link]("Type error occurred");
} else {
throw error;
}
}
Custom Errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
[Link] = "ValidationError";
[Link] = field;
}
}
function validateEmail(email) {
if () {
throw new ValidationError("Invalid email", "email");
}
}
try {
validateEmail("invalid");
} catch (error) {
if (error instanceof ValidationError) {
[Link](`Field "${[Link]}": ${[Link]}`);
}
}
🎨 Object-Oriented Programming
Classes (ES6)
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
return `Hello, I'm ${[Link]}!`;
}
get info() {
return `${[Link]}, ${[Link]} years old`;
}
set setAge(value) {
if (value > 0) [Link] = value;
}
static isAdult(age) {
return age >= 18;
}
}
const person = new Person("John", 30);
[Link](); // "Hello, I'm John!"
[Link](20); // true
Inheritance
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
return `${[Link]} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
[Link] = breed;
}
🐕`;
speak() {
return `${[Link]} barks!
}
fetch() {
return `${[Link]} fetches the ball!`;
}
}
🐕"
const dog = new Dog("Buddy", "Golden Retriever");
[Link](); // "Buddy barks!
Private Fields (ES2022)
class BankAccount {
#balance = 0; // Private field
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
withdraw(amount) {
if (amount <= this.#balance) {
this.#balance -= amount;
return amount;
}
throw new Error("Insufficient funds");
}
get balance() {
return this.#balance;
}
}
const account = new BankAccount(100);
[Link](50);
[Link]([Link]); // 150
// account.#balance; // SyntaxError!
🚀 Advanced Concepts
Closures
// A closure remembers its outer variables
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
// Practical: Private variables
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count,
};
}
Prototypes
function Person(name) {
[Link] = name;
}
[Link] = function () {
return `Hello, I'm ${[Link]}`;
};
const john = new Person("John");
[Link](); // "Hello, I'm John"
// Prototype chain
john.__proto__ === [Link]; // true
[Link].__proto__ === [Link]; // true
Modules (ES6)
// [Link] - Exports
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default class Calculator {}
// [Link] - Imports
import Calculator, { PI, add } from "./[Link]";
import * as MathUtils from "./[Link]";
// Dynamic imports
const module = await import("./[Link]");
Generators
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
[Link](); // { value: 1, done: false }
[Link](); // { value: 2, done: false }
[Link](); // { value: 3, done: false }
[Link](); // { value: undefined, done: true }
for (const num of numberGenerator()) {
[Link](num); // 1, 2, 3
}
📚 Quick Reference
String Methods
const str = "Hello, World!";
[Link]; // 13
[Link](); // "HELLO, WORLD!"
[Link](); // "hello, world!"
[Link](0); // "H"
[Link]("o"); // 4
[Link]("World"); // true
[Link]("Hello"); // true
[Link]("!"); // true
[Link](0, 5); // "Hello"
[Link](", "); // ["Hello", "World!"]
[Link]("World", "JS"); // "Hello, JS!"
[Link](); // Remove whitespace
[Link](15, "*"); // "**Hello, World!"
[Link](2); // "Hello, World!Hello, World!"
Number Methods
const num = 3.14159;
[Link](2); // "3.14"
[Link](); // "3.14159"
[Link](5); // true
[Link](NaN); // true
[Link]("3.14"); // 3.14
[Link]("42px"); // 42
[Link](4.5); // 5
[Link](4.9); // 4
[Link](4.1); // 5
[Link](-5); // 5
[Link](1, 2, 3); // 3
[Link](1, 2, 3); // 1
[Link](2, 3); // 8
[Link](16); // 4
[Link](); // 0 to 0.999...
Date Methods
const now = new Date();
[Link](); // 2024
[Link](); // 0-11 (Jan = 0)
[Link](); // 1-31
[Link](); // 0-6 (Sun = 0)
[Link](); // 0-23
[Link](); // 0-59
[Link](); // Milliseconds since 1970
[Link](); // "2024-01-15T10:30:00.000Z"
[Link](); // "1/15/2024"
[Link](); // "10:30:00 AM"
🎉 Congratulations!
You've completed the JavaScript Cheat Sheet!
Keep practicing and building amazing things! 🚀
📖 Resources
Resource Link
MDN Web Docs [Link]
[Link] [Link]
ES6 Features [Link]
Can I Use [Link]
Made with ❤️ for the JavaScript Community