JavaScript Cheat Sheet
Complete reference guide for JavaScript with interactive examples and live playground links
Basic Syntax
Hello World
Different ways to output text in JavaScript
JavaScript
// Console output
console.log("Hello, World!");
// Alert
alert("Hello, World!");
// DOM manipulation
document.getElementById("greeting").textContent = "Hello, World!";
Variables and Data Types
Variable declaration and basic data types in JavaScript
JavaScript
// Variable declaration
let name = "JavaScript";
const age = 30;
var oldWay = "not recommended";
// Data types
let text = "Hello"; // String
let number = 42; // Number
let decimal = 3.14; // Number
let isActive = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
let symbol = Symbol("id"); // Symbol
let bigInt = 9007199254740991n; // BigInt
// Type checking
console.log(typeof text); // "string"
console.log(typeof number); // "number"
console.log(typeof isActive);// "boolean"
String Operations
Common string operations and template literals
JavaScript
const text = "Hello World";
// String methods
console.log(text.toUpperCase()); // HELLO WORLD
console.log(text.toLowerCase()); // hello world
console.log(text.replace("World", "JS")); // Hello JS
console.log(text.split(" ")); // ["Hello", "World"]
console.log(text.length); // 11
// Template literals
const name = "Alice";
const age = 25;
console.log(`My name is ${name} and I'm ${age} years old`);
// String interpolation
const greeting = `Hello, ${name}!`;
Arrays and Objects
Working with arrays and objects
JavaScript
// Arrays
const fruits = ["apple", "banana", "cherry"];
fruits.push("orange");
fruits.unshift("grape");
fruits.pop();
fruits.shift();
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((a, b) => a + b, 0);
// Objects
const person = {
name: "Alice",
age: 25,
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Object operations
person.job = "Developer";
delete person.age;
const { name, age } = person; // Destructuring
Functions
Different ways to define and use functions
JavaScript
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function
const greet = (name) => `Hello, ${name}!`;
// Function with default parameters
function createUser(name, age = 20) {
return { name, age };
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
// Callback function
function processUser(name, callback) {
const user = { name, id: Date.now() };
callback(user);
}
Modern Features
Destructuring
Destructuring arrays and objects
JavaScript
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [3, 4, 5]
// Object destructuring
const { name, age, ...other } = {
name: "Alice",
age: 25,
job: "Developer",
city: "New York"
};
console.log(name); // "Alice"
console.log(other); // { job: "Developer", city: "New York" }
// Nested destructuring
const { address: { city, country } } = {
name: "Alice",
address: {
city: "New York",
country: "USA"
}
};
Spread and Rest
Spread and rest operators usage
JavaScript
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const obj1 = { foo: "bar" };
const obj2 = { ...obj1, baz: "qux" }; // { foo: "bar", baz: "qux" }
// Rest operator
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
// Combining arrays
const combined = [...arr1, ...arr2];
// Copying objects
const copy = { ...original };
Template Literals
Advanced template literal usage
JavaScript
// Basic usage
const name = "Alice";
const greeting = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
// Tagged templates
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
}, '');
}
const result = highlight`Hello ${name}, welcome to ${site}!`;
Asynchronous Programming
Promises
Working with promises
JavaScript
// Creating a promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 1000);
});
// Using promises
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
// Promise.all
Promise.all([
fetch("/api/users"),
fetch("/api/posts")
])
.then(([users, posts]) => {
// Handle both results
})
.catch(error => {
// Handle any error
});
Async/Await
Modern async/await syntax
JavaScript
// Async function
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error("Error:", error);
}
}
// Using async/await
async function main() {
const user = await fetchUser(1);
console.log(user);
}
// Parallel execution
async function fetchAll() {
const [users, posts] = await Promise.all([
fetch("/api/users"),
fetch("/api/posts")
]);
return { users, posts };
}
DOM Manipulation
Selecting Elements
Selecting and traversing DOM elements
JavaScript
// Different ways to select elements
const element = document.getElementById("myId");
const elements = document.getElementsByClassName("myClass");
const tags = document.getElementsByTagName("div");
// Modern selectors
const element = document.querySelector(".myClass");
const elements = document.querySelectorAll("p");
// Traversing DOM
const parent = element.parentElement;
const children = element.children;
const next = element.nextElementSibling;
const prev = element.previousElementSibling;
Modifying Elements
Modifying DOM elements
JavaScript
// Modifying content
element.textContent = "New text";
element.innerHTML = "<span>HTML content</span>";
// Modifying attributes
element.setAttribute("class", "newClass");
element.classList.add("active");
element.classList.remove("inactive");
element.classList.toggle("visible");
// Modifying styles
element.style.color = "red";
element.style.backgroundColor = "blue";
// Creating elements
const div = document.createElement("div");
div.textContent = "New element";
parent.appendChild(div);
// Removing elements
element.remove();
parent.removeChild(child);
Events and Event Handling
Event Listeners
Working with event listeners
JavaScript
// Adding event listeners
element.addEventListener("click", (event) => {
console.log("Clicked!");
});
// Event object
element.addEventListener("click", (event) => {
console.log(event.target); // Clicked element
console.log(event.currentTarget); // Element with listener
event.preventDefault(); // Prevent default action
event.stopPropagation(); // Stop event bubbling
});
// Removing event listeners
const handler = (event) => console.log("Clicked!");
element.addEventListener("click", handler);
element.removeEventListener("click", handler);
Event Delegation
Event delegation and custom events
JavaScript
// Event delegation
document.getElementById("list").addEventListener("click", (event) => {
if (event.target.matches("li")) {
console.log("List item clicked:", event.target.textContent);
}
});
// Custom events
const event = new CustomEvent("myEvent", {
detail: { message: "Hello" }
});
element.dispatchEvent(event);
// Event bubbling
parent.addEventListener("click", (event) => {
if (event.target === child) {
console.log("Child clicked!");
}
});
JavaScript - Interactive Developer Reference
Hover over code blocks to copy or run in live playground