Javascript
161 bites tagged Javascript — interview questions with model answers, and 60-second explainers.
Shared Workers: One Background Script for Multiple Tabs
A SharedWorker is a single background script shared across multiple tabs or windows from the same origin. Use it to manage a single WebSocket connection or sync state between pages. The footgun: each tab must call `port.start()` on its own message port.
Service Worker Registration: Claiming Your Control Scope
Registering a service worker is like assigning a security guard (your script) to a specific area (the scope) of your site for offline support. The footgun: by default, a worker can only control its own directory, not the whole site.
Web Workers: Keep Your UI Responsive During Heavy Tasks
A Web Worker is like a background helper, running heavy JavaScript tasks in a separate thread so your UI never freezes. Use it for complex calculations or data fetching. The main footgun: workers cannot directly manipulate the DOM.
The `popstate` Event: Handling Browser History Navigation
The `popstate` event lets your app react to browser back/forward clicks. It's key for SPAs to update views without a full reload. The main footgun: the event fires before the document is fully updated, so your handler might read a stale DOM.
Manipulate Browser History with pushState and replaceState
Make a single-page app feel like a multi-page site. `pushState` changes the URL without a full page reload, creating a new browser history entry. This is essential for SPAs to enable shareable links and a working back button.
IndexedDB Versioning: The 'upgradeneeded' Gatekeeper
IndexedDB uses a version number to manage schema changes. Incrementing the version in `indexedDB.open()` triggers a special `upgradeneeded` event, which is the only context where you can create or modify object stores and indexes.
IndexedDB Object Stores: Your Browser's NoSQL Table
An IndexedDB Object Store is like a NoSQL table in your browser, holding JavaScript objects by key. Use it for offline data like to-do lists or cached API responses. The main footgun: you can only create stores during a database version upgrade.
Storing Objects in Web Storage: The JSON Step
Web Storage only stores strings. To save complex data like objects, you must first serialize them with `JSON.stringify()`. This is essential for persisting user settings or session info.
sessionStorage: Tab-Specific Browser Memory
sessionStorage is temporary browser memory isolated to a single tab. Use it to save state within a single user workflow, like form data. The footgun: unlike localStorage, this data is *not* shared between tabs, even for the same site.
localStorage: Your Browser's Persistent Key-Value Store
localStorage is a simple dictionary saved in the browser that persists after the tab closes. Use it to save user settings like a theme. The footgun: all values are strings, so numbers and booleans need manual conversion, like parsing 'true' back to a boolean.
The Headers Object: A Safer Way to Manage HTTP Headers
The `Headers` object is a specialized map for HTTP headers that handles sanitization for you. Use it with the Fetch API to build requests or read response headers. The footgun: headers from a `fetch()` response are immutable and will throw an error if you try.
Fetch API Errors: Why a 404 is a 'Success'
A `fetch()` call only fails on network errors, not on HTTP errors like 404. You must check the `response.ok` property to see if the request was successful. The footgun is assuming a `catch` block will handle a 404; it won't.
Configuring Fetch Requests with `RequestInit`
`RequestInit` is the options object that customizes a `fetch` call beyond a simple GET. Use it to specify the HTTP method, send a request body, set headers, and control caching. A common footgun is sending a JSON body without setting the `Content-Type` header.
Fetch API: Making Basic Network Requests
The Fetch API is like ordering from a catalog: you give it a URL and get a promise of delivery. It's used to load data from APIs without a page reload. The footgun: the promise resolves even on HTTP errors (like 404); you must check.
Promise Cleanup with .finally()
Promise.finally() is the `try...catch...finally` for async code, guaranteeing logic runs after a promise settles. Use it to hide a loading spinner or close a network connection without duplicating code in `.then()` and `.catch()`.
The Promise Constructor: Wrapping Old Callbacks
The `Promise` constructor turns old callback-style functions into modern promises you can `await`. Use it to "promisify" APIs like `setTimeout` that don't return promises. The footgun is wrapping already-promise-based code, creating unnecessary complexity.
The Promise Object: A Placeholder for Future Values
A Promise is an IOU for a value from an async operation, like a network request. It's a placeholder that will eventually hold a result or an error. Use it for fetching data or reading files. The footgun: always add a `.catch()` to handle failures.
Callback Hell: Navigating JavaScript's Async Pyramid
Callback Hell is the 'pyramid of doom' structure from nesting async functions. It happens when chaining I/O tasks like API calls, where each step depends on the last. The footgun is writing async code as if it runs sequentially, creating unreadable nests.
currentTarget vs. target: Who's Listening vs. Who Shouted
event.currentTarget is the element listening for an event, while event.target is the element that triggered it. This is vital for event delegation patterns. Be careful: currentTarget is only valid inside the handler and becomes null afterward.
Accessing data-* Attributes with `dataset`
The `dataset` property is a live map of an element's `data-*` attributes. It automatically converts HTML `data-user-id` to `element.dataset.userId` in JS, perfect for storing state. The footgun: name conversion is lossy; HTML attributes are always lowercased.
Smooth Animations with requestAnimationFrame
Sync your code to the browser's repaint cycle for smooth, efficient animations with `requestAnimationFrame`. Use it for any visual change over time, like moving an element or running a game loop.
The JavaScript Event Loop: Asynchronicity on a Single Thread
The event loop is a queue that lets single-threaded JavaScript handle asynchronous tasks without blocking. It processes callbacks from Web APIs like `fetch` or `setTimeout` one at a time. The footgun: `setTimeout(fn, 0)` doesn't run instantly, just next.
Event Bubbling vs. Capturing: The DOM's Two-Way Street
An event fired on a nested element travels in two phases: first down from the root (capturing), then back up (bubbling). This is how all DOM events work, like clicks.
Browser Object Model: The Browser's Unruly API
The Browser Object Model (BOM) is the collection of non-standard APIs browsers expose for interacting with the browser window. Unlike the standardized DOM, its implementation is up to each vendor, creating a major cross-browser compatibility footgun.
Get Javascript bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.