tips
40 tips Javascript
One command, setting or habit at a time about Javascript: what it does, the line to copy and a caveat or two.
Web development 40
-
Pause a Node.js script on line one so a debugger can attach before anything runs
node --inspect-brk app.js -
Reads a property or calls a function only when the value in front of it exists.
obj?.prop -
Turns a template literal into a string where backslashes stay as written.
const filePath = String.raw`C:\Development\profile\about.html`; -
React to an element's own width changes, from a sidebar toggle or new content.
const observer = new ResizeObserver((entries) => { -
Validate and resolve URLs without exceptions in your normal code path.
URL.parse("not a url"); // null -
Let visitors share a page to any app they have installed, with a fallback for desktops.
shareButton.addEventListener("click", async () => { -
Handle errors from functions that might be sync or async in one catch.
if (!name) throw new Error("No name given"); // sync throw -
One listener on a parent handles clicks on items that are added later.
list.addEventListener("click", (event) => { -
Turn codes like DE or EUR into readable names without a translation file.
const regions = new Intl.DisplayNames(["nl"], { type: "region" }); -
Choose the right plural or ordinal suffix for a number without if statements.
// 1st 2nd 3rd 4th 11th 12th 21st 22nd -
Natural sort order for file names and versions, ignoring upper and lower case.
const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" }); -
Combine several abort reasons into one signal for fetch or any other API.
const signal = AbortSignal.any([ -
Map, filter and limit any iterator lazily, even an endless one.
function* naturals() { -
Group or count items in a Map without the has, set, get dance.
// Map { "jpg" => ["a.jpg", "c.jpg"], "png" => ["b.png"] } -
Store small bits of state in the markup and read them without getAttribute.
delete item.dataset.status; // removes the attribute -
Detect added, removed or changed elements without polling the DOM.
const observer = new MutationObserver((mutations) => { -
Compress a large JSON export or upload with a built-in stream.
const stream = new Blob([text]).stream() -
Script-triggered submits check required fields and fire the submit event, unlike submit().
// submit when the user presses Ctrl+Enter in the textarea -
Add months and count days between calendar dates, without midnight and DST surprises.
const start = Temporal.PlainDate.from("2026-01-31"); -
Stop a phone from dimming while someone follows steps on your page.
let lock = null; -
Get a real character count for limits and truncation, where string length is wrong.
const text = "👍🏽 ok 🇳🇱"; -
React in a script when the visitor switches between light and dark mode.
const dark = window.matchMedia("(prefers-color-scheme: dark)"); -
Search for literal text such as 1.5 (beta)? without the dots and brackets acting as regex syntax.
const query = "1.5 (beta)?"; -
Pauses the page in the script that adds, removes or changes an element.
Elements > right-click #results > Break on > Subtree modifications -
Logs the events fired on the element you last inspected, straight from the Console.
monitorEvents($0, 'click') -
Shows every event listener registered on the element you just inspected.
getEventListeners($0) -
Formats prices and large numbers per language and currency, without your own string code.
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(123456.789); -
Runs code when an element enters the viewport, without listening to every scroll event.
const observer = new IntersectionObserver((entries) => { -
Finds the last array item that matches a test, without reversing or copying the array.
[5, 12, 50, 130, 44].findLast((element) => element > 45); -
Combines two JavaScript sets into a new one with a built-in method.
// Set { "docker", "tmux", "git", "python" } -
Formats a number and a unit as relative time in a chosen language, without a library.
const rtf = new Intl.RelativeTimeFormat("nl", { numeric: "auto" }); -
Writes a string to the clipboard from JavaScript, as long as the page and the moment are allowed.
button.addEventListener("click", async () => { -
Runs several promises together and returns the outcome of each, without stopping at the first rejection.
const results = await Promise.allSettled([ -
Parses and builds URL query strings, with encoding handled for you.
const params = new URLSearchParams({ q: "fiets reparatie", page: 2 }); -
Opens a real modal dialog with a backdrop, focus handling and Escape to close, using one HTML element.
Delete this item? -
Reads an array item by index and counts from the end when the index is negative.
const items = ['a', 'b', 'c']; -
Returns a random version 4 UUID from the browser's secure random generator.
const id = crypto.randomUUID(); -
Groups the items of an array into an object, one array per key you compute.
const files = [ -
Makes a fetch request give up after a set number of milliseconds, without a controller and a timer.
try { -
Returns a new sorted array and leaves the array you started with as it was.
const sorted = names.toSorted();
Nothing in this filter yet.