- Variables & Data Types
- Functions
- Arrays
- Objects
- DOM Manipulation
- Events
- Async/Await & Promises
- ES6+ Features
- Common Patterns
- Performance Tips
// Variable declarations
let variable = "can change";
const constant = "cannot change";
var oldWay = "avoid in modern JS";
// Data types
const string = "Hello World";
const number = 42;
const boolean = true;
const array = [1, 2, 3];
const object = { key: "value" };
const nullValue = null;
const undefinedValue = undefined;
// Type checking
typeof variable;
Array.isArray(array);
variable instanceof Object;
// Type conversion
String(123); // '123'
Number("123"); // 123
Boolean(1); // true
parseInt("123px"); // 123
parseFloat("12.3"); // 12.3// Function declaration
function functionName(param1, param2 = "default") {
return param1 + param2;
}
// Function expression
const func = function (param) {
return param * 2;
};
// Arrow function
const arrow = (param) => param * 2;
const multiLine = (a, b) => {
const sum = a + b;
return sum;
};
// Rest parameters
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
// Destructuring parameters
const greet = ({ name, age = "unknown" }) => `Hello ${name}, age ${age}`;
// IIFE (Immediately Invoked Function Expression)
(function () {
console.log("Runs immediately");
})();
(() => console.log("Arrow IIFE"))();// Array creation
const arr = [1, 2, 3, 4, 5];
const arr2 = new Array(1, 2, 3);
const empty = new Array(5); // 5 empty slots
// Adding/removing elements
arr.push(6); // Add to end
arr.unshift(0); // Add to beginning
arr.pop(); // Remove from end
arr.shift(); // Remove from beginning
arr.splice(2, 1, "x"); // Remove 1 at index 2, add 'x'
// Array methods (non-mutating)
arr.map((x) => x * 2); // Transform each element
arr.filter((x) => x > 2); // Filter elements
arr.reduce((acc, x) => acc + x, 0); // Reduce to single value
arr.find((x) => x > 3); // Find first match
arr.findIndex((x) => x > 3); // Find index of first match
arr.some((x) => x > 5); // Test if any match
arr.every((x) => x > 0); // Test if all match
arr.includes(3); // Check if includes value
arr.indexOf(3); // Get index of value
arr.slice(1, 3); // Extract portion
arr.concat([6, 7]); // Combine arrays
// Destructuring
const [first, second, ...rest] = arr;
const [a, , c] = arr; // Skip second element
// Spread operator
const newArr = [...arr, 6, 7];
const copy = [...arr];// Object creation
const obj = {
key: "value",
method() {
return this.key;
},
[variable]: "dynamic key",
};
// Property access
obj.key; // Dot notation
obj["key"]; // Bracket notation
obj?.key; // Optional chaining
// Property manipulation
obj.newKey = "new value";
delete obj.key;
// Object methods
Object.keys(obj); // ['key1', 'key2']
Object.values(obj); // ['value1', 'value2']
Object.entries(obj); // [['key1', 'value1'], ['key2', 'value2']]
// Copying objects
const copy = { ...obj };
const copy2 = Object.assign({}, obj);
// Destructuring
const { key, method, newKey = "default" } = obj;
const { key: renamedKey } = obj;
// Property shorthand
const name = "John";
const person = { name }; // Same as {name: name}
// Computed properties
const prop = "dynamicKey";
const obj2 = {
[prop]: "value",
[`${prop}2`]: "value2",
};// Selecting elements
document.getElementById("id");
document.querySelector(".class");
document.querySelectorAll(".class");
document.getElementsByClassName("class");
document.getElementsByTagName("tag");
// Element properties
element.textContent = "text";
element.innerHTML = "<span>HTML</span>";
element.value = "input value";
element.setAttribute("attr", "value");
element.getAttribute("attr");
element.removeAttribute("attr");
// CSS classes
element.classList.add("class");
element.classList.remove("class");
element.classList.toggle("class");
element.classList.contains("class");
// Styling
element.style.color = "red";
element.style.backgroundColor = "blue";
// Creating/removing elements
const newEl = document.createElement("div");
newEl.textContent = "New element";
parent.appendChild(newEl);
parent.insertBefore(newEl, parent.firstChild);
element.remove();
// Modern insertion
parent.prepend(newEl); // Add as first child
parent.append(newEl); // Add as last child
parent.before(newEl); // Add before parent
parent.after(newEl); // Add after parent// Event listeners
element.addEventListener("click", function (e) {
console.log("Clicked!");
e.preventDefault(); // Prevent default action
e.stopPropagation(); // Stop event bubbling
});
// Arrow function
element.addEventListener("click", (e) => console.log("Clicked!"));
// Remove listener
element.removeEventListener("click", handlerFunction);
// Common events
"click", "dblclick", "mousedown", "mouseup", "mouseover", "mouseout";
"keydown", "keyup", "keypress";
"submit", "change", "input", "focus", "blur";
"load", "resize", "scroll";
// Event delegation
document.addEventListener("click", (e) => {
if (e.target.matches(".button")) {
console.log("Button clicked");
}
});
// Custom events
const customEvent = new CustomEvent("myEvent", {
detail: { message: "Hello!" },
});
element.dispatchEvent(customEvent);// Creating promises
const promise = new Promise((resolve, reject) => {
if (success) {
resolve(data);
} else {
reject(error);
}
});
// Using promises
promise
.then((data) => console.log(data))
.catch((error) => console.error(error))
.finally(() => console.log("Done"));
// Promise utilities
Promise.all([promise1, promise2]); // Wait for all
Promise.race([promise1, promise2]); // First to complete
Promise.allSettled([promise1, promise2]); // Wait for all to settle
// Async/await
async function fetchData() {
try {
const response = await fetch("/api/data");
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
throw error;
}
}
// Fetch API
fetch("/api/data")
.then((response) => response.json())
.then((data) => console.log(data));
// POST request
fetch("/api/data", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ key: "value" }),
});// Template literals
const name = "John";
const message = `Hello, ${name}!`;
// Destructuring
const [a, b] = [1, 2];
const { x, y } = { x: 1, y: 2 };
// Spread operator
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 };
// Rest parameters
const [first, ...rest] = [1, 2, 3, 4];
// Default parameters
function greet(name = "World") {
return `Hello, ${name}!`;
}
// Object property shorthand
const name2 = "Jane";
const person = { name2 }; // {name2: 'Jane'}
// Method shorthand
const obj2 = {
method() {
return "hello";
},
};
// Classes
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static getSpecies() {
return "Homo sapiens";
}
}
// Modules
export const variable = "value";
export function myFunction() {}
export default class MyClass {}
import MyClass, { variable, myFunction } from "./module.js";
import * as MyModule from "./module.js";// Debounce
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// Throttle
function throttle(func, limit) {
let inThrottle;
return function () {
if (!inThrottle) {
func.apply(this, arguments);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
// Module pattern
const MyModule = (function () {
let privateVar = "private";
return {
publicMethod() {
return privateVar;
},
};
})();
// Factory pattern
function createUser(name, role) {
return {
name,
role,
greet() {
return `Hello, I'm ${this.name}`;
},
};
}
// Observer pattern
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach((callback) => callback(data));
}
}
}// Cache DOM queries
const element = document.getElementById("myElement"); // Cache this
// Use document fragments for multiple insertions
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement("div");
fragment.appendChild(div);
}
document.body.appendChild(fragment);
// Efficient array operations
// Use map, filter, reduce instead of for loops when appropriate
const doubled = numbers.map((n) => n * 2);
const evens = numbers.filter((n) => n % 2 === 0);
// Avoid memory leaks
window.addEventListener("scroll", handler);
// Later...
window.removeEventListener("scroll", handler);
// Use const for objects that won't be reassigned
const config = { api: "url" }; // Use const, not let
// Prefer for...of for arrays, for...in for objects
for (const item of array) {
/* faster */
}
for (const key in object) {
/* for objects */
}
// Use optional chaining to avoid errors
const value = obj?.deep?.nested?.property;
// Batch DOM operations
element.style.cssText = "color: red; background: blue;";
// Better than:
// element.style.color = 'red';
// element.style.background = 'blue';// Conditionals
if (condition) { /* code */ }
condition ? trueValue : falseValue;
value || defaultValue;
value && executeIfTruthy();
// Loops
for (let i = 0; i < length; i++) { /* code */ }
for (const item of array) { /* code */ }
for (const key in object) { /* code */ }
while (condition) { /* code */ }
// Error handling
try {
riskyCode();
} catch (error) {
handleError(error);
} finally {
cleanup();
}
// Local storage
localStorage.setItem('key', value);
localStorage.getItem('key');
localStorage.removeItem('key');
localStorage.clear();
// Date
new Date();
Date.now();
date.getTime();
date.toISOString();
// Math
Math.random();
Math.floor(num);
Math.ceil(num);
Math.round(num);
Math.max(...array);
Math.min(...array);
// JSON
JSON.stringify(object);
JSON.parse(string);
// Regular expressions
/pattern/flags;
string.match(regex);
string.replace(regex, replacement);
regex.test(string);This cheatsheet provides quick access to the most commonly used JavaScript syntax and patterns for rapid development reference.