JavaScript Cheatsheet
A quick JavaScript reference with short examples.

JavaScript Cheatsheet
Core JavaScript, ES6 features and common patterns, each with a short example. Good for a quick refresher.
๐ฆ Basics
// Declare variables
let x = 10; // Block scoped (ES6)
const y = 5; // Constant, also block scoped
var z = 3; // Function scoped (legacy, avoid using)
// Data types
let name = "John"; // string
let age = 30; // number
let isOnline = true; // boolean
let person = { name, age }; // object
let fruits = ["apple", "banana"]; // array
let nothing = null; // null
let notDefined; // undefined๐ก TIP
Prefer let and const over var to avoid scope-related bugs.
๐ Operators
// Arithmetic
+, -, *, /, %, **
// Comparison
==, ===, !=, !==, >, <
// Logical
&&, ||, !
// Assignment
=, +=, -=, *=, /=
// Nullish & Optional
?? // Nullish Coalescing (if null or undefined)
?. // Optional Chaining๐ง NOTE
Always use === instead of == to avoid unexpected type coercion.
๐ง Control Flow
if (condition) {
// ...
} else if (anotherCondition) {
// ...
} else {
// ...
}
switch (value) {
case 1:
break;
default:
break;
}
for (let i = 0; i < 5; i++) { }
while (true) { }
do {
// runs at least once
} while (false);
// Ternary
let result = condition ? "yes" : "no";๐ก TIP
Use switch when checking against multiple fixed values.
๐งฐ Functions
function greet(name) {
return `Hello, ${name}`;
}
const greet = (name) => `Hello, ${name}`;
// Closure Example
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2๐ NOTE
Closures are key in JavaScript. They let functions retain access to variables even after the outer function exits.
๐งฑ Arrays (Common Methods)
const arr = [1, 2, 3, 4];
arr.push(5); // โ Add to end
arr.pop(); // โ Remove from end
arr.unshift(0); // โ Add to start
arr.shift(); // โ Remove from start
arr.includes(3); // ๐ Check if value exists
arr.indexOf(2); // ๐ Index of value
arr.slice(1, 3); // ๐ฆ Copy part of array
arr.splice(1, 1); // ๐ง Remove/replace at index
// Iteration
arr.forEach(n => console.log(n));
// Transformation
const doubled = arr.map(n => n * 2);
// Filtering
const even = arr.filter(n => n % 2 === 0);
// Reducing
const sum = arr.reduce((a, b) => a + b, 0);
// Finding
const found = arr.find(n => n > 2);
arr.sort((a, b) => a - b); // ๐ Sort
arr.reverse(); // ๐ Reverse๐ฌ TIP
Prefer .map, .filter, .reduce for cleaner, functional-style programming.
๐ค Strings (Common Methods)
const str = "Hello, World!";
str.length;
str.toUpperCase();
str.toLowerCase();
str.includes("World");
str.indexOf("l");
str.lastIndexOf("l");
str.substring(0, 5);
str.slice(-6);
str.split(", ");
str.trim();
str.replace("World", "JS");
str.startsWith("Hello");
str.endsWith("!");๐ NOTE
Strings are immutable in JS. All methods return a new string.
๐ Objects
const user = {
name: "Alice",
age: 25,
greet() {
return `Hi ${this.name}`;
}
};
user.name;
user["age"];
user.city = "NYC";
Object.keys(user);
Object.values(user);
Object.entries(user);
Object.hasOwn(user, 'age');
Object.assign({}, user);๐ก TIP
Use Object.entries() + forEach() for key-value iteration.
โณ Promises & Async/Await
const getData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});
};
getData()
.then(console.log)
.catch(console.error);
// Async/Await
async function fetchData() {
try {
const res = await getData();
console.log(res);
} catch (e) {
console.error(e);
}
}โ TIP
Prefer async/await for better readability in async code.
๐ Loops with Arrays
for (let item of arr) {
console.log(item);
}
for (let index in arr) {
console.log(arr[index]);
}
arr.forEach(item => console.log(item));โ ๏ธ NOTE
Avoid using for...in on arrays; it's better for objects.
๐งช Type Checking
typeof 42; // "number"
typeof null; // "object" (quirk!)
Array.isArray([]); // true
if (val == null) {
// true for null or undefined
}
val !== null && typeof val === 'object';๐ TIP
Use Array.isArray() to distinguish between objects and arrays.
๐น๏ธ DOM
// Selecting elements
const el = document.getElementById("id");
const all = document.querySelectorAll("div");
// Modifying elements
el.textContent = "Hello";
el.innerHTML = "<strong>Hi</strong>";
el.style.color = "red";
// Events
el.addEventListener("click", () => alert("Clicked!"));๐ง TIP
Always add event listeners after DOM has loaded or inside DOMContentLoaded.
๐ต Event Loop
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Microtask"));
console.log("End");
// Output:
// Start
// End
// Microtask
// Timeout๐ NOTE
Microtasks (Promises) are executed before macrotasks (setTimeout).
๐งต Storage
localStorage.setItem("name", "John");
localStorage.getItem("name");
sessionStorage.setItem("id", "123");
document.cookie = "user=Ali; path=/; expires=Fri, 31 Dec 2025 23:59:59 GMT";๐ TIP
LocalStorage persists until manually cleared; sessionStorage clears on tab close.
๐ Fetch API
fetch("https://api.example.com")
.then(res => res.json())
.then(data => console.log(data));
async function fetchUser() {
const res = await fetch("https://api.example.com/user");
const user = await res.json();
console.log(user);
}๐ง TIP
Always check .ok in response for error handling.
๐ ES6+ Features
const { name, age } = user; // Object Destructuring
const [a, b] = [1, 2]; // Array Destructuring
const add = (x, y = 0) => x + y;
const nums = [1, 2];
const more = [...nums, 3];
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };
// Optional chaining
user?.address?.city;
// Nullish coalescing
let val = name ?? "Guest";
// Object.hasOwn
Object.hasOwn(user, 'name');
// Template literals
const greetMsg = `Hello, ${name}`;๐ก TIP
Use spread/rest to keep code short and immutable.
๐ฆ Modules
// export.js
export const name = "Imtiyaz";
export default function greet() { }
// import.js
import greet, { name } from "./export.js";๐ฆ NOTE
ES Modules must use .mjs or "type": "module" in package.json.
๐งฉ Misc
// Symbol
const sym = Symbol("id");
// Set
const set = new Set([1, 2, 2]);
set.add(3);
set.has(2);
set.delete(1);
// Map
const map = new Map();
map.set("name", "Ali");
map.get("name");
map.has("name");๐ง TIP
Use Set for uniqueness and Map for complex key-value storage.
๐ Resources
โจ FINAL NOTE
JavaScript evolves quickly. Stay up-to-date, and keep experimenting!

Imtiyaz Nandasaniya
I'm a full-stack developer from Ahmedabad. I post what I learn about code on Instagram as code.clash, in the simplest language I can.
Subscribe to code.clash.
I will email you when I publish a new post. No spam, and you can unsubscribe whenever.
Related Writing.

Free APIs Every Developer Should Know
A list of 25+ free APIs for learning, side projects and trying out ideas.

ReactJS Cheatsheet
JSX, components, hooks, state and performance tips, plus the newer React 18 features.

HTML Cheatsheet
The HTML elements and concepts you use most, with short examples.
Comments (0)
Leave a Comment
No account needed. Anonymous comments are welcome.