JavaScript Cheat Sheet: Syntax, Methods, Async, DOM, Node.js and Testing

This is the quick-reference page for the whole JavaScript course: the syntax and methods you use every day, on one page, each with a link-free one-line explanation and a tested example. Use it to revise before an interview, or keep it open while writing tests. Each section matches a module of the course, so you can jump back to the full lesson for details. Every example below was run on Node.js 26 (browser examples are marked).

Advertisement

📖 What You’ll Learn: a compact reference for variables and types, operators, strings, numbers, arrays, objects, functions, classes, error handling, promises and async/await, modules and npm, DOM and events, browser storage, Node.js files, paths and environment variables, modern features, and the testing and Playwright essentials.


📦 Variables, Types and Operators

SyntaxMeaning
const x = 1 / let y = 2Block-scoped; const cannot be reassigned. Avoid var
typeof x“string”, “number”, “bigint”, “boolean”, “undefined”, “symbol”, “object”, “function”
Array.isArray(x), x === nullReliable checks for arrays and null
=== / !==Strict comparison: always prefer over == and !=
a ?? bb only if a is null or undefined
a || b / a && bFallback for any falsy a / continue only if a is truthy
obj?.a?.b, fn?.()Optional chaining: undefined instead of an error
x ??= 5, x ||= 5, x &&= 5Logical assignment
2 ** 10, 7 % 3Power, remainder
Falsy valuesfalse 0 -0 0n "" null undefined NaN

📄 basics.js

const settings = { retries: 0, user: null };
console.log(settings.retries ?? 3, settings.retries || 3);
console.log(settings.user?.name ?? "guest", typeof settings.user, Array.isArray([]));
console.log(Number("42") + 1, String(42) + 1, Boolean("0"), parseInt("15px"), Number("15px"));

⌨️ Terminal

node basics.js

🖥️ Output

0 3
guest object true
43 421 true 15 NaN

🔤 Strings and Numbers

MethodExample → result
Template literal`Hi ${name}`
length, at(-1)Length; last character
toUpperCase(), toLowerCase(), trim()Case and whitespace
includes(), startsWith(), endsWith(), indexOf()Searching
slice(start, end)Substring (negative indexes count from the end)
split(","), arr.join(",")String ↔ array
replace(a, b), replaceAll(a, b)Replace first / all
padStart(3, "0")“7” → “007”
match(/re/g), test()Regex search (match may return null)
toFixed(2), Math.round(), Number.isInteger()Number formatting and checks
new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" })Locale formatting

📄 strings.js

const title = "  Order #4521 Placed  ";
const clean = title.trim();
console.log(clean.toLowerCase(), clean.includes("#4521"), clean.slice(0, 5), clean.at(-1));
console.log(clean.match(/#(\d+)/)[1], "a,b,c".split(","), "7".padStart(3, "0"));
console.log((0.1 + 0.2).toFixed(2), Math.max(3, 9, 4), new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(123456.5));

⌨️ Terminal

node strings.js

🖥️ Output

order #4521 placed true Order d
4521 [ 'a', 'b', 'c' ] 007
0.30 9 ₹1,23,456.50

📚 Arrays

MethodReturnsMutates?
map(fn)New array of resultsNo
filter(fn)New array of matchesNo
reduce(fn, init)One valueNo
find(fn) / findIndex(fn) / findLast(fn)First match / its index / last matchNo
some(fn) / every(fn) / includes(x)BooleanNo
toSorted(fn), toReversed(), with(i, v)Changed copyNo
sort(fn), reverse(), splice()The same arrayYes
push() / pop() / shift() / unshift()Add/remove at end/startYes
slice(a, b), concat(), [...a, ...b]CopiesNo
flat(), flatMap(fn)Flattened arrayNo
Array.from({ length: n }, fn)Generated array—
Object.groupBy(arr, fn)Object of groupsNo

📄 arrays.js

const runs = [{ t: "login", ms: 1200, ok: true }, { t: "cart", ms: 3100, ok: false }, { t: "search", ms: 800, ok: true }];
console.log(runs.map((r) => r.t), runs.filter((r) => !r.ok).map((r) => r.t));
console.log(runs.reduce((s, r) => s + r.ms, 0), runs.find((r) => r.ms > 1000).t, runs.some((r) => !r.ok), runs.every((r) => r.ms < 5000));
console.log(runs.toSorted((a, b) => a.ms - b.ms).map((r) => r.t), Object.keys(Object.groupBy(runs, (r) => (r.ok ? "passed" : "failed"))));
console.log([...new Set([1, 1, 2])], [[1, 2], [3]].flat(), Array.from({ length: 3 }, (_, i) => i * 2));

⌨️ Terminal

node arrays.js

🖥️ Output

[ 'login', 'cart', 'search' ] [ 'cart' ]
5100 login true true
[ 'search', 'login', 'cart' ] [ 'passed', 'failed' ]
[ 1, 2 ] [ 1, 2, 3 ] [ 0, 2, 4 ]

Advertisement

🗂️ Objects, Maps and Sets

SyntaxMeaning
const { a, b: renamed, c = 1, ...rest } = objDestructuring with rename, default and rest
{ ...obj, a: 2 }Shallow copy with a change
structuredClone(obj)Deep copy
Object.keys / values / entries(obj)Arrays of keys, values, [key, value] pairs
Object.fromEntries(pairs)Pairs → object
"a" in obj, Object.hasOwn(obj, "a")Property exists
Object.freeze(obj)Prevent top-level changes
JSON.stringify(obj, null, 2) / JSON.parse(text)Object ↔ JSON text
new Map(): set, get, has, delete, sizeKey–value store with any key type
new Set(): add, has, delete, size, union, differenceUnique values

📄 objects.js

const user = { name: "Asha", role: "tester", address: { city: "Pune" } };
const { name, role: job, team = "QA", ...rest } = user;
console.log(name, job, team, rest);
console.log(Object.entries({ a: 1, b: 2 }), Object.fromEntries([["env", "qa"]]));
const copy = structuredClone(user);
copy.address.city = "Mumbai";
console.log(user.address.city, JSON.stringify({ ok: true, n: [1, 2] }));
const m = new Map([["login", "passed"]]);
console.log(m.get("login"), m.size, new Set(["a", "b"]).difference(new Set(["b"])));

⌨️ Terminal

node objects.js

🖥️ Output

Asha tester QA { address: { city: 'Pune' } }
[ [ 'a', 1 ], [ 'b', 2 ] ] { env: 'qa' }
Pune {"ok":true,"n":[1,2]}
passed 1 Set(1) { 'a' }

🔧 Functions and Classes

📄 functions.js

// declaration, arrow, default and rest parameters
function add(a, b = 0) { return a + b; }
const sum = (...nums) => nums.reduce((s, n) => s + n, 0);

// closure
const counter = () => { let n = 0; return () => ++n; };
const next = counter();

// class with private field, getter, static, inheritance
class Page {
  static count = 0;
  #visits = 0;
  constructor(url) { this.url = url; Page.count++; }
  open() { this.#visits++; return `open ${this.url}`; }
  get visits() { return this.#visits; }
}
class LoginPage extends Page {
  constructor() { super("/login"); }
  open() { return super.open() + " and wait for form"; }
}
const lp = new LoginPage();
console.log(add(2), sum(1, 2, 3), next(), next());
console.log(lp.open(), lp.visits, Page.count, lp instanceof Page);

⌨️ Terminal

node functions.js

🖥️ Output

2 6 1 2
open /login and wait for form 1 1 true
ConceptOne-line reminder
thisDecided by the call: obj.fn() → obj; arrows inherit; detached methods lose it
call / apply / bindCall with a chosen this / with an args array / return a bound copy
ClosureA function remembers the variables where it was created
HoistingFunction declarations usable before; let/const throw before their line
Higher-orderTakes or returns a function (map, filter, debounce)

⏳ Errors, Promises and async/await

📄 async.mjs

class ApiError extends Error {
  constructor(status, message) { super(message); this.name = "ApiError"; this.status = status; }
}
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

async function getUser(id) {
  await wait(10);
  if (id < 1) throw new ApiError(404, `user ${id} not found`);
  return { id, name: "Asha" };
}

try {
  console.log(await getUser(7));
  await getUser(0);
} catch (e) {
  console.log(e instanceof ApiError, e.name, e.status, e.message);
} finally {
  console.log("finally always runs");
}

console.log(await Promise.all([wait(20, "a"), wait(10, "b")]));
console.log((await Promise.allSettled([getUser(1), getUser(0)])).map((r) => r.status));
console.log(await Promise.race([wait(5, "fast"), wait(50, "slow")]));
const res = await Promise.race([wait(200, "data"), wait(20).then(() => "timeout")]);
console.log(res);

⌨️ Terminal

node async.mjs

🖥️ Output

{ id: 7, name: 'Asha' }
true ApiError 404 user 0 not found
finally always runs
[ 'a', 'b' ]
[ 'fulfilled', 'rejected' ]
fast
timeout
Remember
OrderSync code → microtasks (then, await) → macrotasks (setTimeout, I/O)
Parallelawait Promise.all(items.map(fn)); sequential: for...of with await
NeverforEach(async ...) (does not wait), return in finally, missing await
fetchDoes not reject on 404/500: check res.ok; timeouts with AbortSignal.timeout(ms)

Advertisement

🧩 Modules, npm and Node.js

TaskCode / command
ES module export / importexport const x = 1; · import { x } from "./file.js";
Default exportexport default class Page {} · import Page from "./page.js";
Enable ESM for .js"type": "module" in package.json
Folder of current file (ESM)import.meta.dirname (CommonJS: __dirname)
Install packagesnpm install pkg · dev: npm install -D pkg · CI: npm ci
Run a script / a binarynpm run lint · npx playwright test
Read and write filesawait fs.readFile(p, "utf8") · await fs.writeFile(p, text) from node:fs/promises
Build a pathpath.join(import.meta.dirname, "data", "users.json")
Environment variablesprocess.env.BASE_URL ?? "http://localhost:3000" · node --env-file=.env app.js
Command-line argumentsparseArgs from node:util; process.argv
Exit with failureprocess.exitCode = 1

📄 node.mjs

import { readFile, writeFile, mkdir } from "node:fs/promises";
import path from "node:path";

const dir = path.join("out", "reports");
await mkdir(dir, { recursive: true });
const file = path.join(dir, "summary.json");
await writeFile(file, JSON.stringify({ passed: 18, failed: 2 }));
const summary = JSON.parse(await readFile(file, "utf8"));
console.log(summary.passed + summary.failed, "tests", "| env:", process.env.TEST_ENV ?? "local", "| ext:", path.extname(file));

⌨️ Terminal

node node.mjs

🖥️ Output

20 tests | env: local | ext: .json

🌐 DOM, Events and Storage (browser)

TaskCode
Selectdocument.querySelector(css), querySelectorAll(css), el.closest(css)
Read / write textel.textContent (safe), el.innerHTML (trusted HTML only)
Attributes and datael.getAttribute("href"), el.dataset.testid
Classes and stylesel.classList.add/remove/toggle("x"), getComputedStyle(el)
Create and insertdocument.createElement("li"), parent.append(el), el.remove()
Eventsel.addEventListener("click", fn, { once: true }), e.preventDefault()
Delegationlist.addEventListener("click", (e) => e.target.closest(".delete") && ...)
Formsnew FormData(form), input.checkValidity(), setCustomValidity(msg)
StoragelocalStorage.setItem(k, JSON.stringify(v)), JSON.parse(localStorage.getItem(k))
Cookiesdocument.cookie = "k=v; max-age=3600; path=/" (HttpOnly cookies are invisible)

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <ul id="list"><li data-id="1">Login test</li></ul>
  <button id="add">Add</button>
  <script src="app.js"></script>
</body>
</html>

📄 app.js

const list = document.querySelector("#list");
document.querySelector("#add").addEventListener("click", () => {
  const li = document.createElement("li");
  li.textContent = "Cart test";
  li.dataset.id = "2";
  list.append(li);
  localStorage.setItem("count", String(list.children.length));
  console.log([...list.children].map((x) => `${x.dataset.id}:${x.textContent}`), localStorage.getItem("count"));
});

🖥️ Browser console (browser, after clicking Add)

["1:Login test","2:Cart test"] 2

🧪 Testing and Playwright Essentials

ToolEssentials
node:testimport { test, describe, mock } from "node:test" · assert.equal / deepEqual / throws / await rejects · node --test
Jest / Vitestexpect(x).toBe / toEqual / toContain / toThrow · jest.fn() / vi.fn() · test.each
Fake timemock.timers.enable() · vi.useFakeTimers() · Playwright page.clock
Playwright locatorspage.getByRole("button", { name: "Save" }), getByLabel, getByText, getByTestId
Playwright actionsawait locator.fill("x"), click(), check(), selectOption(), press("Enter")
Web-first assertionsawait expect(locator).toBeVisible() / toHaveText() / toHaveCount(), await expect(page).toHaveURL()
API testsasync ({ request }) => { const res = await request.get("/api/users"); expect(res.ok()).toBeTruthy(); }
Run and debugnpx playwright test · --ui · --debug · show-report · codegen

📄 package.json

{ "type": "module" }

📄 cheat.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

const applyCoupon = (total, code) => (code === "SQA10" ? total * 0.9 : total);

test("SQA10 gives 10% off", () => assert.equal(applyCoupon(1000, "SQA10"), 900));
test("unknown coupon leaves the total", () => assert.equal(applyCoupon(1000, "X"), 1000));

⌨️ Terminal

node --test cheat.test.js

🖥️ Output

✔ SQA10 gives 10% off (1.0542ms)
✔ unknown coupon leaves the total (0.1854ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 141.5513

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. From memory: which array methods change the original array?

Show answer

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin. Their safe copies are toSorted, toReversed, toSpliced and with.

Q2. Write one line that returns the names of failed tests, sorted alphabetically, without changing the input.

Show answer

📄 p2.js

const runs = [{ name: "search", ok: false }, { name: "login", ok: true }, { name: "cart", ok: false }];
console.log(runs.filter((r) => !r.ok).map((r) => r.name).toSorted());

🖥️ Output

[ 'cart', 'search' ]

Q3. Write a safe reader for a numeric environment variable with a default.

Show answer

📄 p3.js

const intEnv = (name, fallback) => {
  const n = Number(process.env[name]);
  return Number.isFinite(n) && process.env[name] !== undefined ? n : fallback;
};
console.log(intEnv("RETRIES_NOT_SET", 2));

🖥️ Output

2

Q4. Convert an array of pairs to an object and back.

Show answer

📄 p4.js

const obj = Object.fromEntries([["env", "qa"], ["workers", 4]]);
console.log(obj, Object.entries(obj));

🖥️ Output

{ env: 'qa', workers: 4 } [ [ 'env', 'qa' ], [ 'workers', 4 ] ]

Q5. Run three async tasks in parallel and print their results in order.

Show answer

📄 p5.mjs

const job = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));
console.log(await Promise.all([job("A", 30), job("B", 10), job("C", 20)]));

🖥️ Output

[ 'A', 'B', 'C' ]

Q6. Name the Playwright locator you would use for: a “Sign in” button, an input labelled “Email”, and an element with data-testid=”cart-count”.

Show answer

page.getByRole("button", { name: "Sign in" }), page.getByLabel("Email"), page.getByTestId("cart-count").


🧠 MCQ Quiz: JavaScript Cheat Sheet

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which operator gives a default only for null or undefined?
  2. Which string method returns null when nothing matches?
  3. Which array method returns a single value?
  4. Which creates a deep copy?
  5. How do you run promises in parallel and wait for all?
  6. Which enables ES modules for .js files?
  7. Which is the safe way to set user text in the DOM?
  8. Which command installs exactly what package-lock.json lists?
  9. Which Playwright assertion waits until an element shows text?
  10. What does fetch do on a 404 response?

💼 Interview Questions and Answers

Q1. How would you revise JavaScript the evening before an interview?

Skim this cheat sheet section by section, explain each row aloud with an example, re-run a few event-loop and this puzzles from the senior lesson, solve three coding programs without help, and prepare two short stories about bugs you found or automation you built. Sleep matters more than one more hour of reading.

Q2. Which five JavaScript features do you use most in test automation?

async/await (every browser and API step), destructuring (fixtures and responses), array methods (map, filter, find on data and locator results), template literals (URLs, selectors, messages), and modules/classes (page objects, helpers). Optional chaining and nullish coalescing come close behind for safe data handling.

Q3. What are the most common JavaScript mistakes in test code?

Missing await, async callbacks in forEach, == instead of ===, mutating shared fixtures, fixed sleeps instead of waiting for state, relying on test order, swallowing errors in try/catch without rethrowing, and reading environment variables without defaults or validation.

Q4. Where do you look things up?

MDN Web Docs for the language and browser APIs, the Node.js documentation for built-in modules, the Playwright docs for testing, and running a small snippet in Node.js or the browser console to confirm behaviour before relying on memory.


Advertisement

❓ Frequently Asked Questions

🤔 Can I print this cheat sheet?

Yes: use your browser’s Print (Ctrl+P) and choose “Save as PDF”. The tables print well in landscape.

🤔 Is this enough to learn JavaScript?

No: it is a reference. Learn each topic from the full lessons in this course first, then use this page to revise.

🤔 Does it cover TypeScript?

No. TypeScript adds types on top of everything here; the Playwright TypeScript course on SQA Tools teaches it in a testing context.

🤔 How do I keep up with new JavaScript features?

Each June a new ECMAScript edition is published; the ES6 to ES2026 lesson summarises the important ones, and MDN marks newly available features.


🏁 Summary

  • const/let, ===, ?? and ?. prevent most beginner bugs; know the eight falsy values.
  • Know which string and array methods return copies and which mutate; prefer toSorted and spread.
  • Destructuring, structuredClone, Map and Set, and JSON are the everyday object tools.
  • async/await with Promise.all for parallel work; check res.ok with fetch; never forEach(async).
  • Modules, npm, fs/path/env for Node.js; textContent and delegation in the DOM; node:test, Jest/Vitest and Playwright web-first assertions for testing.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in