JavaScript Cheat Sheet: Full Guide
Variables
var x = 1; // function-scoped
let y = 2; // block-scoped
const z = 3; // block-scoped, constant
Data Types
String, Number, Boolean, Undefined, Null, BigInt, Symbol, Object, Array, Function
Functions
function greet(name) { return "Hi " + name; }
const greet2 = (name) => "Hi " + name;
Arrays & Objects
let arr = [1, 2, 3];
arr.map(x => x * 2);
arr.filter(x => x > 1);
let obj = { name: "Alice", age: 25 };
console.log(obj.name);
Control Flow
if (x > 0) { }
for (let i = 0; i < 5; i++) { }
switch (x) { case 1: break; default: break; }
Async
async function getData() {
let res = await fetch(url);
let data = await res.json();
return data;
}
Keep this cheat sheet handy as a quick reference while practicing JavaScript fundamentals.
Strings, Destructuring and Spread
const name = "Priya Sharma";
name.length; // 12
name.toUpperCase(); // "PRIYA SHARMA"
name.includes("Sharma"); // true
name.split(" "); // ["Priya", "Sharma"]
name.slice(0, 5); // "Priya"
`Hello, ${name}!`; // template literal
const [first, second] = [10, 20]; // array destructuring
const { city, age = 18 } = { city: "Pune" }; // object destructuring with a default
const merged = { ...{ a: 1 }, b: 2 }; // spread copies properties
const all = [...[1, 2], 3]; // [1, 2, 3]
Strings are immutable: methods such as toUpperCase() return a new string and leave the original unchanged. Destructuring pulls values out of arrays by position and out of objects by property name, and spread is the quick way to make shallow copies.
More Array Methods and Loops
| Method | Returns | Example result for [5, 12, 8] |
|---|---|---|
find(x => x > 6) | First matching item | 12 |
findIndex(x => x > 6) | Index of the first match | 1 |
some(x => x > 10) | True if any item matches | true |
every(x => x > 1) | True if all items match | true |
reduce((s, x) => s + x, 0) | A single combined value | 25 |
includes(8) | True if the value is present | true |
push(1) / pop() | Add to or remove from the end | changes the array |
for (const n of [5, 12, 8]) console.log(n); // values
for (const key in { a: 1, b: 2 }) console.log(key); // property names
Object.keys(obj); Object.values(obj); Object.entries(obj);
Use for...of for array values and for...in only for object keys. Methods such as map and filter return new arrays, while push, pop and sort change the original array in place.
Safer Comparisons, Errors, Classes and the DOM
0 == "0"; // true (loose: converts types)
0 === "0"; // false (strict: no conversion)
user?.address?.pin; // optional chaining: undefined instead of an error
input ?? "N/A"; // nullish coalescing: fallback only for null/undefined
try {
JSON.parse("{bad json}");
} catch (err) {
console.error("Parsing failed:", err.message);
} finally {
console.log("Done");
}
class Account {
#balance = 0; // private field
deposit(amount) { this.#balance += amount; return this; }
get balance() { return this.#balance; }
}
export function add(a, b) { return a + b; } // in math.js
import { add } from "./math.js"; // in another module
const btn = document.querySelector("#save");
btn.addEventListener("click", () => {
document.querySelector(".msg").textContent = "Saved!";
});
const [users, posts] = await Promise.all([fetch("/users"), fetch("/posts")]);
A few habits prevent most beginner bugs. Prefer === so values are compared without hidden type conversion. Reach for const by default and use let only when a variable must be reassigned; avoid var in new code. Use textContent rather than innerHTML when showing user-supplied text, which keeps pages safe from injected markup.
Gotchas Worth Memorising
| Expression | Result | Why |
|---|---|---|
typeof null | "object" | A long-standing quirk of the language |
0.1 + 0.2 === 0.3 | false | Floating-point rounding; compare with a small tolerance |
[10, 9, 1].sort() | [1, 10, 9] | Default sort compares text; pass (a, b) => a - b |
"5" + 2 | "52" | + joins strings when either side is text |
"5" - 2 | 3 | - always converts to numbers |
[] == false | true | Loose equality converts both sides; use === |
With asynchronous code, remember that await works inside async functions and at the top level of modules. Promise.all runs independent requests in parallel and fails as soon as any one of them rejects, while Promise.allSettled waits for every result. Always handle errors from fetch, and check res.ok, because a 404 or 500 response does not throw on its own.
Ready to master real-world JavaScript development?
Learn JavaScript hands-on with mentor-led, live sessions.