JavaScript Cheatsheet
Keep this sheet handy for everyday JavaScript in the browser or Node. Definitions stay short; examples show the usual shape of the code.
Work through the JavaScript tutorials when you want fuller explanations and practice exercises.
Full lessons: JavaScript Tutorials
Language basics
console.log
Prints values to the developer console. Useful for quick checks while learning.
console.log("ready", 42);
console.log({ ok: true });
let / const / var
Prefer const for bindings that do not reassign, let for ones that do. Avoid var in modern code.
const name = "Ada";
let count = 0;
count += 1;
Comments
Single-line // and multi-line /* */ comments. Use them to clarify intent.
// one line
/* multi
line */
Template literals
Backtick strings support ${expressions} and multi-line text.
const user = "Sam";
console.log(`Hello, ${user}!`);
Strict mode
"use strict" enables stricter parsing and error handling. Modules are strict by default.
"use strict";
// undeclared assignments throw
Values & operators
Primitives
Common primitives: number, string, boolean, null, undefined, bigint, and symbol.
const n = 10;
const s = "hi";
const ok = true;
const empty = null;
typeof
Returns a string naming the value's type. Note: typeof null is "object" (legacy quirk).
typeof 3; // "number"
typeof "x"; // "string"
typeof null; // "object"
=== vs ==
=== compares without type coercion. Prefer === / !== unless you intentionally want loose equality.
1 === "1"; // false
1 == "1"; // true (avoid)
Arithmetic & assignment
Standard math operators plus +=, -=, ++, and --. Division always yields a float in JS numbers.
let x = 10;
x += 2;
console.log(x / 4); // 3
Logical operators
&&, ||, and ! short-circuit. ?? returns the right side only when the left is null or undefined.
const name = null ?? "guest";
const ready = true && "go";
Arrays
Ordered lists. Length is mutable; many methods return new arrays (map, filter) while others mutate (push).
const nums = [3, 1, 4];
nums.push(1);
console.log(nums[0], nums.length);
Functions & objects
Function declaration
Named functions are hoisted. Parameters may have defaults.
function greet(name = "friend") {
return `Hi, ${name}`;
}
console.log(greet("Maya"));
Arrow functions
Concise function expressions. They do not bind their own this—useful for callbacks.
const add = (a, b) => a + b;
const double = n => n * 2;
Objects
Key/value maps. Dot or bracket access; shorthand properties and methods are common.
const user = { name: "Lee", age: 20 };
user.age = 21;
console.log(user["name"]);
Destructuring
Unpack arrays or objects into variables in one statement.
const [a, b] = [1, 2];
const { name, age } = { name: "Kim", age: 19 };
Spread / rest
... expands iterables into arguments or elements, or gathers remaining args into an array.
const more = [...[1, 2], 3];
function sum(...nums) {
return nums.reduce((t, n) => t + n, 0);
}
this (methods)
In a normal method call, this is the object before the dot. Arrow functions inherit this from the enclosing scope.
const counter = {
n: 0,
bump() { this.n += 1; },
};
counter.bump();
DOM & events
querySelector
Finds the first element matching a CSS selector. querySelectorAll returns a NodeList.
const btn = document.querySelector("#save");
const items = document.querySelectorAll("li");
textContent / value
Read or set text on elements. Use .value for inputs, textareas, and selects.
const el = document.querySelector("h1");
el.textContent = "Updated";
const input = document.querySelector("input");
console.log(input.value);
classList
Add, remove, or toggle CSS classes without rewriting the whole className string.
const box = document.querySelector(".box");
box.classList.add("open");
box.classList.toggle("active");
addEventListener
Attach a handler for an event type. Prefer this over inline onclick attributes.
const btn = document.querySelector("button");
btn.addEventListener("click", (event) => {
console.log("clicked", event.target);
});
preventDefault
Stops the browser's default action (for example, form submit navigation).
form.addEventListener("submit", (e) => {
e.preventDefault();
// handle locally
});
Async
Promises
Represent a future value. Chain with then/catch or await inside async functions.
fetch("/api/data")
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err));
async / await
Write asynchronous code that looks sequential. Await only works inside async functions (or modules at top level in modern runtimes).
async function load() {
const res = await fetch("/api/data");
if (!res.ok) throw new Error(res.status);
return res.json();
}
try / catch with await
Wrap awaited calls so network or parse failures become catchable errors.
async function safeLoad() {
try {
return await load();
} catch (err) {
console.error(err);
return null;
}
}
JSON
JSON.parse turns a string into a value; JSON.stringify does the reverse.
const obj = JSON.parse('{"a":1}');
const text = JSON.stringify(obj, null, 2);
setTimeout / setInterval
Run code after a delay or on a repeating timer. Clear with clearTimeout / clearInterval.
const id = setTimeout(() => console.log("later"), 1000);
// clearTimeout(id);
Promise.all
Waits for every promise to fulfill, then resolves to an array of results. Rejects if any input rejects.
const [a, b] = await Promise.all([
fetch("/a").then(r => r.json()),
fetch("/b").then(r => r.json()),
]);
Comments
One comment per signed-in account. Comments are saved with this page’s URL.