JavaScript Cheat Sheet: Modern ES6+ Syntax and Array Methods
Introduction
This JavaScript cheat sheet covers the modern syntax you use every day in browsers and Node.js. Copy a snippet, adjust it, and move on. For deeper explanations, use the JavaScript lessons on this site.
Prerequisites
- A browser console or Node.js
Step-by-Step Guide
Step 1: Variables and types
Prefer const, use let when a value changes, and avoid var. Compare with === instead of ==.
const name = "Ada";
let count = 0;
typeof name; // "string"
const items = [1, 2, 3];
const user = { name: "Ada", age: 36 };
null; undefined; NaN;
Number("42"); String(42); Boolean(0);
5 === "5"; // false (strict)
user?.address?.city; // optional chaining -> undefined
const city = user.city ?? "unknown"; // nullish coalescingStep 2: Strings and template literals
Template literals use backticks and can embed expressions and span lines.
const greeting = `Hello, ${name}! You have ${count} messages.`;
"hello".toUpperCase();
"a,b,c".split(",");
" hi ".trim();
"hello".includes("ell");
"hello".slice(1, 3); // "el"
"ab".repeat(3); // "ababab"
"abc".padStart(5, "0"); // "00abc"Step 3: Functions
Arrow functions are short and do not have their own this. Default and rest parameters make signatures flexible.
function add(a, b = 0) { return a + b; }
const multiply = (a, b) => a * b;
const double = n => n * 2;
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);
setTimeout(() => console.log("later"), 1000);Step 4: Destructuring and spread
Destructuring pulls values out of arrays and objects. Spread copies or merges them without changing the original.
const [first, second, ...rest] = [1, 2, 3, 4];
const { name, age = 18, ...others } = user;
const copy = [...items, 4];
const merged = { ...user, role: "admin" };
function show({ name, age }) { console.log(name, age); }Step 5: Array methods you will use daily
map, filter, and reduce return new values and do not change the original array.
const nums = [1, 2, 3, 4, 5];
nums.map(n => n * 2); // [2, 4, 6, 8, 10]
nums.filter(n => n % 2 === 0); // [2, 4]
nums.reduce((total, n) => total + n, 0); // 15
nums.find(n => n > 3); // 4
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true
nums.includes(3); // true
nums.slice(1, 3); nums.at(-1);
[...nums].sort((a, b) => b - a); // copy, then sort
Object.keys(user); Object.values(user); Object.entries(user);Step 6: Promises and async/await
Mark a function async to use await. Always handle errors with try/catch and check response.ok when using fetch.
async function getUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error("failed:", error);
throw error;
}
}
const [a, b] = await Promise.all([getUser(1), getUser(2)]);
await Promise.allSettled([getUser(1), getUser(2)]);Step 7: Modules and the DOM
ES modules use import and export. The DOM methods below work in the browser.
// math.js
export const PI = 3.14159;
export default function add(a, b) { return a + b; }
// app.js
import add, { PI } from "./math.js";
const button = document.querySelector("#save");
button.addEventListener("click", event => {
event.preventDefault();
button.textContent = "Saved";
button.classList.toggle("active");
});
document.querySelectorAll(".item").forEach(el => el.remove());
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");FAQs
- What is the difference between == and ===?
- == converts types before comparing, which causes surprises. === compares value and type, so use it by default.
Summary
Use const and let, arrow functions, destructuring and spread, array methods, async/await with error handling, and ES modules. These patterns cover most modern JavaScript.
Related tutorials
- Linux Command Line Cheat Sheet: Files, Permissions, Processes, and Networking
- Docker and kubectl Cheat Sheet: Containers, Images, Compose, and Kubernetes
- SQL Cheat Sheet: SELECT, Joins, Aggregates, and Data Changes
- Git Cheat Sheet: Everyday Commands, Branching, and Undoing Mistakes
- Langflow Cheat Sheet: Install, Components, API Calls, and Custom Components
Comments
Log in or create a free account to join the discussion.