Skip to content

Commit db88a2d

Browse files
committed
qns: make JavaScript answers more practical
Audit all 193 English answers against a practical interview rubric and improve the 130 answers with concrete gaps in examples, tradeoffs, failure modes, or current platform guidance. Regenerate the README so its embedded TL;DR sections stay synchronized while preserving metadata and translations.
1 parent 8800d6d commit db88a2d

131 files changed

Lines changed: 2754 additions & 2641 deletions

File tree

  • questions
    • describe-event-capturing
    • describe-the-difference-between-script-async-and-script-defer
    • difference-between-document-load-event-and-document-domcontentloaded-event
    • explain-ajax-in-as-much-detail-as-possible
    • explain-event-delegation
    • explain-how-jsonp-works-and-how-its-not-really-ajax
    • explain-how-prototypal-inheritance-works
    • explain-how-this-works-in-javascript
    • explain-the-concept-of-a-callback-function-in-asynchronous-operations
    • explain-the-concept-of-a-microtask-queue
    • explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance
    • explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality
    • explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security
    • explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques
    • explain-the-concept-of-error-propagation-in-javascript
    • explain-the-concept-of-hoisting-with-regards-to-functions
    • explain-the-concept-of-inheritance-in-es2015-classes
    • explain-the-concept-of-input-validation-and-its-importance-in-security
    • explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance
    • explain-the-concept-of-tagged-templates
    • explain-the-concept-of-test-driven-development-tdd
    • explain-the-concept-of-the-prototype-pattern
    • explain-the-concept-of-the-singleton-pattern
    • explain-the-concept-of-the-strategy-pattern
    • explain-the-concept-of-the-web-socket-api
    • explain-the-concept-of-this-binding-in-event-handlers
    • explain-the-concept-of-tree-shaking-in-module-bundling
    • explain-the-difference-between-documentqueryselector-and-documentgetelementbyid
    • explain-the-difference-between-mutable-and-immutable-objects
    • explain-the-difference-between-synchronous-and-asynchronous-functions
    • explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing
    • explain-the-differences-between-commonjs-modules-and-es-modules
    • explain-the-different-states-of-a-promise
    • explain-the-different-ways-the-this-keyword-can-be-bound
    • explain-the-observer-pattern-and-its-use-cases
    • explain-the-same-origin-policy-with-regards-to-javascript
    • explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly
    • how-can-you-create-custom-error-objects
    • how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications
    • how-can-you-optimize-dom-manipulation-for-better-performance
    • how-can-you-optimize-network-requests-for-better-performance
    • how-can-you-prevent-clickjacking-attacks
    • how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications
    • how-can-you-share-code-between-files
    • how-can-you-test-asynchronous-code-in-javascript
    • how-do-iframe-on-a-page-communicate
    • how-do-you-abort-a-web-request-using-abortcontrollers
    • how-do-you-add-remove-and-modify-html-elements-using-javascript
    • how-do-you-add-remove-and-update-elements-in-an-array
    • how-do-you-check-if-an-object-has-a-specific-property
    • how-do-you-check-the-data-type-of-a-variable
    • how-do-you-convert-a-string-to-a-number-in-javascript
    • how-do-you-handle-errors-in-asynchronous-operations
    • how-do-you-import-and-export-modules-in-javascript
    • how-do-you-make-an-http-request-using-the-fetch-api
    • how-do-you-organize-your-code-module-pattern-classical-inheritance
    • how-do-you-redirect-to-a-new-page-in-javascript
    • how-do-you-reliably-determine-whether-an-object-is-empty
    • how-do-you-use-windowhistory-api
    • how-do-you-validate-form-elements-using-the-constraint-validation-api
    • how-do-you-write-unit-tests-for-javascript-code
    • how-does-hoisting-affect-function-declarations-and-expressions
    • how-does-javascript-garbage-collection-work
    • how-is-promiseall-different-from-promiseallsettled
    • what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor
    • what-are-callback-functions-and-how-are-they-used
    • what-are-default-parameters-and-how-are-they-used
    • what-are-design-patterns-and-why-are-they-useful
    • what-are-event-listeners-and-how-are-they-used
    • what-are-iterators-and-generators-and-what-are-they-used-for
    • what-are-javascript-object-getters-and-setters-for
    • what-are-javascript-polyfills-for
    • what-are-mocks-and-stubs-and-how-are-they-used-in-testing
    • what-are-progressive-web-applications-pwas
    • what-are-promises-and-how-do-they-work
    • what-are-proxies-in-javascript-used-for
    • what-are-server-sent-events
    • what-are-some-best-practices-for-handling-sensitive-data-in-javascript
    • what-are-some-best-practices-for-writing-maintainable-and-effective-tests
    • what-are-some-common-performance-bottlenecks-in-javascript-applications
    • what-are-some-common-security-headers-and-their-purpose
    • what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript
    • what-are-some-techniques-for-reducing-reflows-and-repaints
    • what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code
    • what-are-some-tools-that-can-be-used-for-javascript-testing
    • what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance
    • what-are-symbols-used-for
    • what-are-the-advantages-and-disadvantages-of-using-ajax
    • what-are-the-benefits-of-using-a-module-bundler
    • what-are-the-differences-between-map-set-and-weakmap-weakset
    • what-are-the-differences-between-xmlhttprequest-and-fetch
    • what-are-the-different-methods-for-iterating-over-an-array
    • what-are-the-different-types-of-errors-in-javascript
    • what-are-the-different-types-of-testing-in-software-development
    • what-are-the-different-ways-to-copy-an-object-or-an-array
    • what-are-the-different-ways-to-make-an-api-call-in-javascript
    • what-are-the-metadata-fields-of-a-module
    • what-are-the-potential-issues-caused-by-hoisting
    • what-are-the-potential-pitfalls-of-using-closures
    • what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks
    • what-are-the-various-data-types-in-javascript
    • what-are-the-various-ways-to-create-objects-in-javascript
    • what-are-web-workers-and-how-can-they-be-used-to-improve-performance
    • what-are-workers-in-javascript-used-for
    • what-do-you-think-of-amd-vs-commonjs
    • what-is-a-closure-and-how-why-would-you-use-one
    • what-is-asyncawait-and-how-does-it-simplify-asynchronous-code
    • what-is-cross-site-scripting-xss-and-how-can-you-prevent-it
    • what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue
    • what-is-objectfreeze-for
    • what-is-objectpreventextensions-for
    • what-is-objectseal-for
    • what-is-recursion-and-how-is-it-used-in-javascript
    • what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript
    • what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation
    • what-is-the-difference-between-innerhtml-and-textcontent
    • what-is-the-difference-between-settimeout-setimmediate-and-processnexttick
    • what-is-the-intl-namespace-object-for
    • what-is-the-module-pattern-and-how-does-it-help-with-encapsulation
    • what-is-the-purpose-of-the-finally-block
    • what-is-the-purpose-of-the-new-keyword
    • what-is-the-use-of-promiseall
    • what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it
    • what-tools-and-techniques-do-you-use-for-debugging-javascript-code
    • whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states
    • when-would-you-use-document-write
    • why-you-might-want-to-create-static-class-members

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 371 additions & 479 deletions
Large diffs are not rendered by default.

‎questions/describe-event-capturing/en-US.mdx‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,27 @@ title: Describe event capturing in JavaScript and browsers
44

55
## TL;DR
66

7-
Event capturing is a lesser-used counterpart to [event bubbling](/questions/quiz/describe-event-bubbling) in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.
7+
Event capturing is a lesser-used counterpart to [event bubbling](/questions/quiz/describe-event-bubbling) in the DOM event propagation mechanism. During capture, the event travels along its event path from ancestors toward the target, and capture listeners run in that order.
88

9-
Event capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on `addEventListener()`.
9+
Event capturing is used less often than event bubbling, but it is useful when an ancestor needs to observe an event before it reaches the target. DOM events still travel through the capture phase; what defaults to `false` is the `capture` option when registering a listener with `addEventListener()`.
1010

1111
---
1212

1313
## What is event capturing?
1414

1515
Event capturing is a propagation mechanism in the DOM (Document Object Model) where an event, such as a click or a keyboard event, is first triggered at the root of the document and then flows down through the DOM tree to the target element.
1616

17-
Capturing has a higher priority than bubbling, meaning that capturing event handlers are executed before bubbling event handlers, as shown by the phases of event propagation:
17+
Capture listeners run before bubble listeners because capture is the first phase of DOM event propagation:
1818

1919
- **Capturing phase**: The event moves down towards the target element
2020
- **Target phase**: The event reaches the target element
2121
- **Bubbling phase**: The event bubbles up from the target element
2222

23-
Note that event capturing is disabled by default. To enable it, you have to pass the capture option into `addEventListener()`.
23+
Listeners are registered for the bubbling phase by default. Pass `true` as the third argument, or `{ capture: true }`, to register a capture listener.
2424

2525
## Capturing phase
2626

27-
During the capturing phase, the event starts at the document root and propagates down to the target element. Any event listeners on ancestor elements in this path will be triggered before the target element's handler. Note that event capturing will not happen unless the third argument of `addEventListener()` is set to `true` as shown below (the default value is `false`).
27+
During the capturing phase, the event travels from the top of the event path down toward the target. Capture listeners on ancestors in this path run before the target's listeners. The propagation phase exists regardless of whether any capture listeners are registered.
2828

2929
Here's an example demonstrating event capturing:
3030

@@ -127,7 +127,7 @@ The full picture: events go down, then up. Capture handlers fire from the root t
127127
| --- | --- | --- |
128128
| Phase order | First (down from root) | Last (up to root) |
129129
| `useCapture` argument | `true` (or `{ capture: true }`) | `false` (the default) |
130-
| Default behavior | Off; must opt in | On; every listener bubbles by default |
130+
| Listener registration default | Must opt in with `{ capture: true }` | Default (`capture: false`) |
131131
| Effect of `event.stopPropagation()` | Stops the event before it reaches the target | Stops the event before higher ancestors see it |
132132
| Common use cases | Intercepting non-bubbling events; pre-empting child handlers; analytics | Most click, input, and change handlers; event delegation |
133133

‎questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx‎

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ title: Describe the difference between a cookie, `sessionStorage` and `localStor
44

55
## TL;DR
66

7-
All of the following are mechanisms of storing data on the client, the user's browser in this case. `localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).
7+
Cookies, `localStorage`, and `sessionStorage` all store data in the browser, but they differ in lifetime, scope, server interaction, and security controls. `localStorage` and `sessionStorage` implement the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).
88

9-
- **Cookies**: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.
10-
- **`localStorage`**: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.
11-
- **`sessionStorage`**: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.
9+
- **Cookies**: Small values that the browser sends with matching HTTP requests. They can be session or persistent cookies and support controls such as `HttpOnly`, `Secure`, and `SameSite`.
10+
- **`localStorage`**: Origin-scoped string storage that persists until it is cleared and is shared by same-origin tabs and windows.
11+
- **`sessionStorage`**: Origin- and tab-scoped string storage for a page session. It survives reloads but is normally cleared when the tab or window closes.
1212

1313
Here's a table summarizing the 3 client storage mechanisms.
1414

@@ -17,30 +17,30 @@ Here's a table summarizing the 3 client storage mechanisms.
1717
| Initiator | Client or server. Server can use `Set-Cookie` header | Client | Client |
1818
| Lifespan | As specified | Until deleted | Until tab is closed |
1919
| Persistent across browser sessions | If a future expiry date is set | Yes | No |
20-
| Sent to server with every HTTP request | Yes, sent via `Cookie` header | No | No |
21-
| Typical storage limit | About 4 KB per cookie | About 5 MB per origin (browser-dependent) | About 5 MB per origin (browser-dependent) |
20+
| Sent to server with matching HTTP requests | Yes, via the `Cookie` header | No | No |
21+
| Typical storage limit | About 4 KB per cookie | Browser-dependent quota, commonly several MiB per origin | Browser-dependent quota, commonly several MiB per origin |
2222
| Access | Across windows/tabs | Across windows/tabs | Same tab |
2323
| Security | JavaScript cannot access `HttpOnly` cookies | None | None |
2424

2525
---
2626

2727
## Storage on the web
2828

29-
Cookies, `localStorage`, and `sessionStorage`, are all storage mechanisms on the client (web browser). It is useful to store data on the client for client-only state like access tokens, themes, personalized layouts, so that users can have a consistent experience on a website across tabs and usage sessions.
29+
Cookies, `localStorage`, and `sessionStorage` are browser storage mechanisms. Client storage is useful for state such as themes, personalized layouts, draft form data, and identifiers needed by a server session. Sensitive authentication credentials require a threat-model-specific design; they should not be placed in Web Storage by default.
3030

3131
These client-side storage mechanisms have the following common properties:
3232

33-
- This means the clients can read and modify the values (except for `HttpOnly` cookies).
33+
- Client-side JavaScript can read and modify the values, except for `HttpOnly` cookies.
3434
- Key-value based storage.
3535
- They are only able to store values as strings. Non-strings will have to be serialized into a string (e.g. `JSON.stringify()`) in order to be stored.
3636

3737
### Use cases for each storage mechanism
3838

3939
Since cookies have a relatively low maximum size, it is not advisable to store all your client-side data within cookies. The distinguishing properties about cookies are that cookies are sent to the server on every HTTP request so the low maximum size is a feature that prevents your HTTP requests from being too large due to cookies. Automatic expiry of cookies is a useful feature as well.
4040

41-
With that in mind, the best kind of data to store within cookies is small pieces of data that need to be transmitted to the server, such as auth tokens, session IDs, analytics tracking IDs, GDPR cookie consent, language preferences that are important for authentication, authorization, and rendering on the server. These values are sometimes sensitive and can benefit from the `HttpOnly`, `Secure`, and `Expires`/`Max-Age` capabilities that cookies provide.
41+
With that in mind, cookies suit small values that the server needs, such as opaque session identifiers, analytics identifiers, consent choices, or language preferences used during server rendering. Sensitive cookies can benefit from `HttpOnly`, `Secure`, and `SameSite`; `Expires` or `Max-Age` controls persistence. The server must still validate and authorize every request.
4242

43-
`localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API). Web Storage has a generous total capacity of 5MB, so storage size is usually not a concern. The key difference is that values stored in Web Storage are not automatically sent along with HTTP requests.
43+
`localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API). Their quota is browser-dependent and can be exceeded, so applications should handle `QuotaExceededError`. Values stored in Web Storage are not automatically sent with HTTP requests.
4444

4545
While you can manually include values from Web Storage when making AJAX/`fetch()` requests, the browser does not include them in the initial request / first load of the page. Hence Web Storage should not be used to store data that is relied on by the server for the initial rendering of the page if server-side rendering is being used (typically authentication/authorization-related information). `localStorage` is most suitable for user preferences data that do not expire, like themes and layouts (if it is not important for the server to render the final layout). `sessionStorage` is most suitable for temporary data that only needs to be accessible within the current browsing session, such as form data (useful to preserve data during accidental reloads).
4646

@@ -51,22 +51,22 @@ The following sections dive deeper into each client storage mechanism.
5151
Cookies are used to store small pieces of data on the client side that can be sent back to the server with every HTTP request.
5252

5353
- **Storage capacity**: Limited to around 4 KB per cookie. Browsers also limit how many cookies can be stored per domain.
54-
- **Lifespan**: Cookies can have a specific expiration date set using the `Expires` or `Max-Age` attributes. If no expiration date is set, the cookie is deleted when the browser is closed (session cookie).
54+
- **Lifespan**: Cookies can have a specific expiration date set using the `Expires` or `Max-Age` attributes. Without one, they are session cookies, although browsers may restore session cookies as part of session restore.
5555
- **Access**: Cookies are domain-specific and can be shared across different pages and subdomains within the same domain.
5656
- **Security**: Cookies can be marked as `HttpOnly` to prevent access from JavaScript, reducing the risk of XSS attacks. They can also be secured with the `Secure` flag to ensure they are sent only when HTTPS is used.
5757

5858
```js
59-
// Set a cookie for the name/key `auth_token` with an expiry.
59+
// Set a non-sensitive preference cookie with an expiry.
6060
document.cookie =
61-
'auth_token=abc123def; expires=Fri, 31 Dec 2100 23:59:59 GMT; path=/';
61+
'theme=dark; expires=Fri, 31 Dec 2100 23:59:59 GMT; path=/; SameSite=Lax; Secure';
6262

6363
// Read all cookies. There's no way to read specific cookies using `document.cookie`.
6464
// You have to parse the string yourself.
65-
console.log(document.cookie); // auth_token=abc123def
65+
console.log(document.cookie); // theme=dark
6666

67-
// Delete the cookie with the name/key `auth_token` by setting an
67+
// Delete the cookie with the name/key `theme` by setting an
6868
// expiry date in the past. The value doesn't matter.
69-
document.cookie = 'auth_token=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
69+
document.cookie = 'theme=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
7070
```
7171

7272
It is a pain to read/write to cookies. `document.cookie` returns a single string containing all the key/value pairs delimited by `;` and you have to parse the string yourself. The [`js-cookie`](https://github.com/js-cookie/js-cookie) npm library provides a simple and lightweight API for reading/writing cookies in JavaScript.
@@ -75,16 +75,16 @@ A modern native way of accessing cookies is via the [Cookie Store API](https://d
7575

7676
```js
7777
// Set a cookie. More options are available too.
78-
cookieStore.set('auth_token', 'abc123def');
78+
cookieStore.set('theme', 'dark');
7979

8080
// Async method to access a single cookie and do something with it.
81-
cookieStore.get('auth_token').then(...);
81+
cookieStore.get('theme').then(...);
8282

8383
// Async method to get all cookies.
8484
cookieStore.getAll().then(...);
8585

8686
// Async method to delete a single cookie.
87-
cookieStore.delete('auth_token').then(() =>
87+
cookieStore.delete('theme').then(() =>
8888
console.log('Cookie deleted')
8989
);
9090
```
@@ -148,12 +148,12 @@ A side-by-side feature comparison hides the most important practical difference
148148
| `Secure` flag (HTTPS-only transport) | Yes | N/A (values never leave the client unless your code sends them) |
149149
| `SameSite` flag (CSRF defense: `Strict`, `Lax`, `None`) | Yes | N/A |
150150
| Partitioned cookies (CHIPS, isolated per top-level site) | Yes (modern browsers) | N/A |
151-
| Survives an XSS exploit | An `HttpOnly` cookie does | All values are exfiltrable |
151+
| Can an injected script read the value? | Not if the cookie is `HttpOnly` | Yes |
152152

153153
The practical takeaways:
154154

155-
- **Auth and session tokens belong in `HttpOnly; Secure; SameSite=Lax` cookies, not in `localStorage`.** Any XSS bug in any script on the origin can read everything in `localStorage`. An `HttpOnly` cookie cannot be read by JavaScript at all, so the attacker would have to make requests through the user's browser, which CSRF defenses (`SameSite`, double-submit tokens) are designed to block.
156-
- **CSRF vs XSS is the trade-off.** Cookies need CSRF protection; `localStorage` tokens (with the Authorization-header pattern) do not. The cookie plus `SameSite=Lax` combination is generally considered safer because it survives XSS, and `SameSite=Lax` blocks the most common CSRF cases by default.
155+
- **Opaque session identifiers are commonly stored in `HttpOnly; Secure; SameSite=Lax` cookies.** Any injected script on the origin can read Web Storage. `HttpOnly` prevents it from reading the cookie value, but it does not make the application survive XSS: the script may still perform authenticated same-origin actions or steal data visible to the page.
156+
- **Cookie authentication needs CSRF defenses.** `SameSite` mitigates many cross-site requests, and applications may also validate CSRF tokens, `Origin`, or Fetch Metadata. These controls do not stop a script already executing on the application's own origin.
157157
- **`localStorage` is fine for non-sensitive client state**: theme preferences, layout settings, draft text, recently viewed items.
158158

159159
## Real-world set, get, and remove
@@ -173,22 +173,21 @@ sessionStorage.removeItem('draft');
173173

174174
// Cookie: modern async API (where supported)
175175
await cookieStore.set({
176-
name: 'session',
177-
value: 'abc123',
176+
name: 'theme',
177+
value: 'dark',
178178
sameSite: 'Lax',
179179
secure: true,
180180
expires: Date.now() + 7 * 24 * 60 * 60 * 1000,
181181
});
182-
const session = await cookieStore.get('session');
183-
await cookieStore.delete('session');
182+
const theme = await cookieStore.get('theme');
183+
await cookieStore.delete('theme');
184184

185185
// Cookie: legacy `document.cookie` API (universally supported)
186-
document.cookie =
187-
'session=abc123; Path=/; Max-Age=604800; SameSite=Lax; Secure';
186+
document.cookie = 'theme=dark; Path=/; Max-Age=604800; SameSite=Lax; Secure';
188187
// Reading a specific cookie still requires parsing the string yourself:
189188
const value = document.cookie
190189
.split('; ')
191-
.find((row) => row.startsWith('session='))
190+
.find((row) => row.startsWith('theme='))
192191
?.split('=')[1];
193192
```
194193

0 commit comments

Comments
 (0)