JavaScript Cheat Sheet
Learn JavaScript from the basics →
Variables
let x = "value";- Reassignable variable
const x = "value";- Not reassignable (block-scoped)
`Hello, ${name}`- Template literal interpolation
typeof x- Get a variable's type
Arrays
[1, 2, 3]- Array literal
arr.length- Array length
arr.map(fn)- Transform each element
arr.filter(fn)- Keep matching elements
arr.reduce(fn, initial)- Reduce to a single value
Strings
str.length- String length
str.toLowerCase() / toUpperCase()- Change case
str.includes(needle)- Check for a substring
str.trim()- Remove surrounding whitespace
str.split(",")- Split into an array
Control Flow
if / else if / else- Conditional branching
for (const x of arr)- Loop over values
switch (x) { case 1: ... }- Switch statement
Functions
function f(x) { return x; }- Function declaration
(x) => x * 2- Arrow function
async function f() { await g(); }- Async/await
Classes
class User { constructor(name) { this.name = name; } }- Class with constructor
new User("Ada")- Instantiate
class Admin extends User { }- Inheritance
Async
fetch(url).then(r => r.json())- Fetch data (Promise-based)
const data = await fetch(url)- Fetch with async/await
Promise.all([p1, p2])- Wait for several promises
try { await f(); } catch (e) { }- Catch an async error
DOM
document.querySelector(".btn")- Select the first matching element
el.addEventListener("click", fn)- Listen for an event
el.textContent = "Hi"- Set an element's text
el.classList.add("active")- Add a CSS class
Modules & Packages
export function f() { }- Export from a module
import { f } from "./file.js"- Import from a module
npm install express- Install a package