Appearance
JavaScript - Modern Web Development
Complete JavaScript reference for modern web development and ES6+ features
JavaScript is the programming language of the web, enabling interactive websites, server-side development, and mobile applications. This comprehensive guide covers modern JavaScript syntax, DOM manipulation, async programming, and popular frameworks.
Variables and Data Types
Variable Declarations
javascript
// var (function-scoped, avoid in modern code)
var oldStyle = "avoid this";
// let (block-scoped, mutable)
let count = 0;
let message = "Hello";
// const (block-scoped, immutable reference)
const PI = 3.14159;
const user = { name: "Alice" }; // Object contents can change
const numbers = [1, 2, 3]; // Array contents can change
// Destructuring assignment
const person = { name: "Alice", age: 30, city: "NYC" };
const { name, age } = person;
const { name: userName, age: userAge } = person; // Rename variables
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
const [primary, ...secondary] = colors; // Rest operator
Data Types
javascript
// Primitive types
const string = "Hello World";
const number = 42;
const bigint = 123n;
const boolean = true;
const undefined = undefined;
const nullValue = null;
const symbol = Symbol("unique");
// Object types
const object = { key: "value" };
const array = [1, 2, 3];
const function = () => {};
const date = new Date();
const regex = /pattern/g;
// Type checking
typeof variable; // Returns type as string
Array.isArray(variable); // Check if array
variable instanceof Object; // Check instance type
variable === null; // Check for null
variable == null; // Check for null or undefined
Functions
Function Declarations and Expressions
javascript
// Function declaration (hoisted)
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const greet = function(name) {
return `Hello, ${name}!`;
};
// Arrow functions (ES6+)
const greet = (name) => {
return `Hello, ${name}!`;
};
// Concise arrow functions
const greet = name => `Hello, ${name}!`;
const add = (a, b) => a + b;
const square = x => x * x;
// Default parameters
function greet(name = "World") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Spread operator
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5, 6];
const result = sum(...numbers);
Advanced Function Concepts
javascript
// Higher-order functions
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
// Immediately Invoked Function Expression (IIFE)
(function() {
console.log("This runs immediately");
})();
// Closures
function counter() {
let count = 0;
return function() {
return ++count;
};
}
const increment = counter();
// Method shorthand (ES6+)
const obj = {
name: "Alice",
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Computed property names
const property = "dynamicKey";
const obj = {
[property]: "value",
[`${property}2`]: "another value"
};
Arrays and Array Methods
Array Creation and Basic Operations
javascript
// Array creation
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];
const empty = [];
const fromRange = Array.from({length: 5}, (_, i) => i + 1); // [1,2,3,4,5]
// Array access and modification
numbers[0]; // First element
numbers[numbers.length - 1]; // Last element
numbers.push(6); // Add to end
numbers.pop(); // Remove from end
numbers.unshift(0); // Add to beginning
numbers.shift(); // Remove from beginning
numbers.splice(2, 1, 99); // Remove 1 element at index 2, insert 99
Array Methods (Functional Programming)
javascript
const numbers = [1, 2, 3, 4, 5];
// map - Transform each element
const doubled = numbers.map(x => x * 2);
const strings = numbers.map(x => x.toString());
// filter - Select elements that match condition
const evens = numbers.filter(x => x % 2 === 0);
const positives = numbers.filter(x => x > 0);
// reduce - Combine elements into single value
const sum = numbers.reduce((total, num) => total + num, 0);
const max = numbers.reduce((max, num) => Math.max(max, num));
const product = numbers.reduce((prod, num) => prod * num, 1);
// find - Find first matching element
const found = numbers.find(x => x > 3); // Returns 4
const foundIndex = numbers.findIndex(x => x > 3); // Returns 3
// some/every - Test conditions
const hasEven = numbers.some(x => x % 2 === 0); // true
const allPositive = numbers.every(x => x > 0); // true
// forEach - Execute function for each element
numbers.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
// sort - Sort array (modifies original)
const words = ["banana", "apple", "cherry"];
words.sort(); // Alphabetical
numbers.sort((a, b) => a - b); // Numerical ascending
numbers.sort((a, b) => b - a); // Numerical descending
// includes - Check if element exists
numbers.includes(3); // true
words.includes("apple"); // true
Advanced Array Operations
javascript
// Chaining methods
const result = numbers
.filter(x => x > 2)
.map(x => x * 2)
.reduce((sum, x) => sum + x, 0);
// flat - Flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
// flatMap - Map then flatten
const words = ["hello", "world"];
words.flatMap(word => word.split('')); // ['h','e','l','l','o','w','o','r','l','d']
// Array.from - Create array from iterable
Array.from("hello"); // ['h', 'e', 'l', 'l', 'o']
Array.from({length: 3}, (_, i) => i); // [0, 1, 2]
// Spread operator with arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const copy = [...arr1]; // Shallow copy
Objects
Object Creation and Manipulation
javascript
// Object literal
const person = {
name: "Alice",
age: 30,
city: "New York",
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Property access
person.name; // Dot notation
person["name"]; // Bracket notation
person["first-name"]; // Required for special characters
// Dynamic property access
const property = "name";
person[property]; // "Alice"
// Object methods
Object.keys(person); // Get all keys
Object.values(person); // Get all values
Object.entries(person); // Get key-value pairs
Object.assign({}, person); // Shallow copy
Object.freeze(person); // Make immutable
Object.seal(person); // Prevent adding/removing properties
// Destructuring with objects
const { name, age, city = "Unknown" } = person;
const { name: personName } = person; // Rename variable
// Rest operator with objects
const { name, ...rest } = person;
Advanced Object Concepts
javascript
// Object shorthand (ES6+)
const name = "Alice";
const age = 30;
const person = { name, age }; // Same as { name: name, age: age }
// Computed property names
const key = "dynamicProperty";
const obj = {
[key]: "value",
[`${key}2`]: "another value"
};
// Object spread operator
const defaults = { theme: "dark", language: "en" };
const userPrefs = { language: "es", fontSize: 14 };
const settings = { ...defaults, ...userPrefs }; // Merge objects
// Optional chaining (ES2020)
const user = { profile: { address: { street: "123 Main St" } } };
user.profile?.address?.street; // Safe property access
user.profile?.phone?.number; // undefined (no error)
// Nullish coalescing (ES2020)
const value = null;
const defaultValue = value ?? "default"; // "default"
const zero = 0;
const result = zero ?? "default"; // 0 (not "default")
// Object.defineProperty for advanced control
Object.defineProperty(obj, 'property', {
value: 'value',
writable: false,
enumerable: true,
configurable: false
});
Asynchronous Programming
Promises
javascript
// Creating promises
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("Operation successful!");
} else {
reject(new Error("Operation failed!"));
}
}, 1000);
});
// Using promises
promise
.then(result => {
console.log(result);
return "Next step";
})
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error.message);
})
.finally(() => {
console.log("Cleanup");
});
// Promise utilities
Promise.all([promise1, promise2, promise3]) // Wait for all
.then(results => console.log(results));
Promise.allSettled([promise1, promise2]) // Wait for all (no fail-fast)
.then(results => console.log(results));
Promise.race([promise1, promise2]) // First to complete
.then(result => console.log(result));
Promise.resolve("immediate value"); // Resolved promise
Promise.reject(new Error("immediate error")); // Rejected promise
Async/Await
javascript
// Async function declaration
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Async arrow function
const fetchUser = async (id) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
};
// Using async functions
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/await with Promise.all
async function fetchMultipleUsers() {
try {
const [user1, user2, user3] = await Promise.all([
fetchUser(1),
fetchUser(2),
fetchUser(3)
]);
return { user1, user2, user3 };
} catch (error) {
console.error('Error fetching users:', error);
}
}
// Sequential vs parallel execution
async function sequential() {
const result1 = await operation1(); // Wait for completion
const result2 = await operation2(); // Then start this
return [result1, result2];
}
async function parallel() {
const promise1 = operation1(); // Start immediately
const promise2 = operation2(); // Start immediately
const result1 = await promise1; // Wait for first
const result2 = await promise2; // Wait for second
return [result1, result2];
}
DOM Manipulation
Selecting Elements
javascript
// Single element selection
document.getElementById('myId');
document.querySelector('.myClass');
document.querySelector('#myId');
document.querySelector('div.myClass');
document.querySelector('[data-attribute="value"]');
// Multiple element selection
document.getElementsByClassName('myClass');
document.getElementsByTagName('div');
document.querySelectorAll('.myClass');
document.querySelectorAll('div.myClass');
// Traversing the DOM
element.parentNode;
element.parentElement;
element.children;
element.childNodes;
element.firstElementChild;
element.lastElementChild;
element.nextElementSibling;
element.previousElementSibling;
Modifying Elements
javascript
// Content manipulation
element.textContent = "New text content";
element.innerHTML = "<strong>HTML content</strong>";
element.innerText = "Visible text only";
// Attribute manipulation
element.getAttribute('data-id');
element.setAttribute('data-id', 'newValue');
element.removeAttribute('data-id');
element.hasAttribute('data-id');
// Class manipulation
element.classList.add('newClass');
element.classList.remove('oldClass');
element.classList.toggle('activeClass');
element.classList.contains('someClass');
element.className = "class1 class2 class3";
// Style manipulation
element.style.color = 'red';
element.style.backgroundColor = 'blue';
element.style.fontSize = '16px';
element.style.display = 'none';
// Creating and inserting elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello World';
newDiv.classList.add('myClass');
parent.appendChild(newDiv);
parent.insertBefore(newDiv, referenceElement);
parent.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');
// Removing elements
element.remove();
parent.removeChild(element);
Event Handling
javascript
// Adding event listeners
button.addEventListener('click', function(event) {
console.log('Button clicked!');
event.preventDefault(); // Prevent default behavior
event.stopPropagation(); // Stop event bubbling
});
// Arrow function event handlers
button.addEventListener('click', (event) => {
console.log('Button clicked!');
});
// Event delegation (for dynamic content)
document.addEventListener('click', (event) => {
if (event.target.matches('.dynamic-button')) {
console.log('Dynamic button clicked!');
}
});
// Common events
element.addEventListener('click', handler);
element.addEventListener('mouseover', handler);
element.addEventListener('mouseout', handler);
element.addEventListener('keydown', handler);
element.addEventListener('keyup', handler);
element.addEventListener('change', handler);
element.addEventListener('input', handler);
element.addEventListener('submit', handler);
element.addEventListener('load', handler);
element.addEventListener('resize', handler);
// Removing event listeners
element.removeEventListener('click', handler);
// Event object properties
function handleClick(event) {
event.target; // Element that triggered event
event.currentTarget; // Element with event listener
event.type; // Event type ('click', 'keydown', etc.)
event.clientX; // Mouse X coordinate
event.clientY; // Mouse Y coordinate
event.key; // Key pressed (for keyboard events)
event.preventDefault(); // Prevent default behavior
event.stopPropagation(); // Stop event bubbling
}
Modern JavaScript Features
Template Literals
javascript
// Basic template literals
const name = "Alice";
const age = 30;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;
// Multi-line strings
const html = `
<div class="card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// Expression evaluation
const price = 19.99;
const tax = 0.08;
const total = `Total: $${(price * (1 + tax)).toFixed(2)}`;
// Tagged template literals
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + string + value;
}, '');
}
const highlighted = highlight`Hello ${name}, you are ${age} years old.`;
Modules (ES6+)
javascript
// Exporting (math.js)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// Default export
export default function subtract(a, b) {
return a - b;
}
// Importing
import subtract, { PI, add, multiply } from './math.js';
import * as math from './math.js';
import { add as addition } from './math.js'; // Rename import
// Dynamic imports
async function loadModule() {
const module = await import('./math.js');
return module.add(2, 3);
}
Classes (ES6+)
javascript
// Basic class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
// Getter
get info() {
return `${this.name} (${this.age})`;
}
// Setter
set age(value) {
if (value < 0) throw new Error('Age cannot be negative');
this._age = value;
}
// Static method
static compare(person1, person2) {
return person1.age - person2.age;
}
}
// Inheritance
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call parent constructor
this.grade = grade;
}
greet() {
return `${super.greet()}, I'm in grade ${this.grade}`;
}
}
// Private fields (ES2022)
class BankAccount {
#balance = 0; // Private field
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
Error Handling
Try/Catch/Finally
javascript
// Basic error handling
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('This always runs');
}
// Specific error types
try {
JSON.parse(invalidJson);
} catch (error) {
if (error instanceof SyntaxError) {
console.error('Invalid JSON syntax');
} else {
console.error('Unknown error:', error);
}
}
// Async error handling
async function handleAsyncErrors() {
try {
const data = await fetchData();
return data;
} catch (error) {
console.error('Fetch failed:', error);
throw error; // Re-throw if needed
}
}
// Custom errors
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
function validateEmail(email) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email format');
}
}
This comprehensive JavaScript cheat sheet covers modern ES6+ features, DOM manipulation, asynchronous programming, and best practices for effective web development. Master these concepts to build powerful, interactive web applications.