JavaScript Cheat Sheet
Basics
Variables
let x = 5; // Block-scoped, mutable
const y = 10; // Block-scoped, immutable
var z = 15; // Function-scoped (avoid in modern JS)
Data Types
// Primitives
let num = 42; // Number
let str = "Hello"; // String
let bool = true; // Boolean
let undef; // Undefined
let nul = null; // Null
let sym = Symbol(); // Symbol
// Non-primitives
let obj = { key: "value" }; // Object
let arr = [1, 2, 3]; // Array
let func = () => {}; // Function
Type Conversion
String(123); // "123"
Number("42"); // 42
Boolean(1); // true
parseInt("10px"); // 10
parseFloat("3.14"); // 3.14
Operators
Arithmetic
5 + 2; // 7
5 - 2; // 3
5 * 2; // 10
5 / 2; // 2.5
5 % 2; // 1 (modulus)
5 ** 2; // 25 (exponentiation)
Comparison
5 == "5"; // true (loose equality)
5 === "5"; // false (strict equality)
5 != "5"; // false
5 !== "5"; // true
5 > 2; // true
5 <= 5; // true
Logical
true && false; // false (AND)
true || false; // true (OR)
!true; // false (NOT)
Ternary Operator
let age = 18;
let canVote = age >= 18 ? "Yes" : "No";
Functions
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
Arrow Function
const greet = (name) => `Hello, ${name}!`;
Default Parameters
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
Rest Parameters
function sum(...nums) {
return nums.reduce((a, b) => a + b);
}
sum(1, 2, 3); // 6
Arrays
Common Methods
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
arr.unshift(0); // [0, 2, 3]
arr.slice(1, 2); // [2] (non-destructive)
arr.splice(1, 1); // [0, 3] (destructive)
arr.concat([4, 5]); // [0, 3, 4, 5]
Iteration
arr.forEach((item) => console.log(item));
let doubled = arr.map((item) => item * 2);
let filtered = arr.filter((item) => item > 1);
let sum = arr.reduce((acc, val) => acc + val, 0);
Objects
Object Literal
let person = {
name: "Alice",
age: 25,
greet() {
console.log(`Hello, ${this.name}!`);
}
};
Accessing Properties
person.name; // "Alice"
person["age"]; // 25
let key = "name";
person[key]; // "Alice"
Destructuring
let { name, age } = person;
console.log(name, age); // "Alice" 25
Spread Operator
let newPerson = { ...person, age: 26 };
Control Flow
Conditionals
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}
Loops
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// For...of (arrays)
for (let num of [1, 2, 3]) {
console.log(num);
}
// For...in (objects)
for (let key in person) {
console.log(key, person[key]);
}
Error Handling
try {
// Risky code
throw new Error("Oops!");
} catch (err) {
console.error(err.message);
} finally {
console.log("Always runs");
}
Promises & Async/Await
Promise
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
promise.then((res) => console.log(res));
Async/Await
async function fetchData() {
try {
let res = await fetch("https://api.example.com");
let data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
DOM Manipulation
// Selectors
document.getElementById("id");
document.querySelector(".class");
document.querySelectorAll("p");
// Modify Elements
element.textContent = "New text";
element.innerHTML = "<strong>Bold</strong>";
element.style.color = "red";
element.classList.add("active");
// Events
element.addEventListener("click", (e) => {
console.log("Clicked!");
});
ES6+ Features
- Template Literals:
`Hello, ${name}!`
- Destructuring:
let [a, b] = [1, 2];
- Spread/Rest:
[...arr], {...obj}
- Modules:
import/export
- Optional Chaining:
obj?.prop?.nested
- Nullish Coalescing:
value ?? "default"
This cheat sheet covers the essentials of JavaScript. Bookmark it for quick reference! 🚀