JavaScript Cheatsheet
JavaScript is the language of the web. This cheatsheet covers modern ES6+ syntax, arrays, objects, and async patterns.
JavaScript is the programming language of the web, running in browsers and on servers via Node.js. This cheatsheet covers modern (ES6+) syntax and common patterns.
Variables
Prefer const and let over var.
const name = "Ada"; // block-scoped, constant
let count = 0; // block-scoped, reassignable
var old = "avoid"; // function-scoped (legacy)
Functions
Arrow functions and defaults.
function add(a, b) { return a + b; }
const mul = (a, b) => a * b;
const greet = (name = "friend") => `Hi ${name}`;
Arrays
Powerful built-in methods.
const nums = [1, 2, 3];
nums.map(n => n * 2); // [2, 4, 6]
nums.filter(n => n > 1); // [2, 3]
nums.reduce((a, b) => a + b) // 6
nums.find(n => n === 2); // 2
nums.includes(3); // true
[...nums, 4]; // spread -> [1,2,3,4]
Objects
Destructuring and spread.
const user = { id: 1, name: "Ada" };
const { name } = user; // destructure
const copy = { ...user }; // shallow copy
const merged = { ...user, age: 36 };
Object.keys(user); // ['id', 'name']
Template Literals
String interpolation and multiline.
const msg = `Hello ${name}, you have ${count} items`;
const html = `
<div>${name}</div>
`;
Conditionals
Ternaries and short-circuiting.
const label = count > 0 ? "has" : "empty";
const value = input ?? "default"; // nullish coalescing
user?.address?.city; // optional chaining
Async / Await
Handle promises cleanly.
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
return await res.json();
} catch (err) {
console.error(err);
}
}
Promises
Compose asynchronous work.
fetch("/api")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Promise.all([p1, p2]).then(([a, b]) => {});
Modules
Import and export.
export const pi = 3.14;
export default function () {}
import defaultFn, { pi } from "./math.js";
JavaScript powers interactivity on the web and full-stack apps on Node.js. Learn these fundamentals, then explore frameworks like React and runtimes like Node and Deno.
For full documentation, see https://developer.mozilla.org/en-US/docs/Web/JavaScript