Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ This list contains the top essential questions that are frequently-asked during
| 21 | [Describe event bubbling in JavaScript and browsers](#describe-event-bubbling-in-javascript-and-browsers) | Basic |
| 22 | [Describe event capturing in JavaScript and browsers](#describe-event-capturing-in-javascript-and-browsers) | Basic |
| 23 | [What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?](#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers) | Basic |
| 24 | [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for) | Advanced |
| 24 | [What is `'use strict';` (strict mode) in JavaScript for?](#what-is-use-strict-strict-mode-in-javascript-for) | Advanced |
| 25 | [Explain the difference between synchronous and asynchronous functions in JavaScript](#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript) | Basic |
| 26 | [What are the pros and cons of using Promises instead of callbacks in JavaScript?](#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript) | Intermediate |
| 27 | [Explain AJAX in as much detail as possible](#explain-ajax-in-as-much-detail-as-possible) | Basic |
Expand Down Expand Up @@ -276,13 +276,13 @@ This list contains a longer list of important JavaScript questions. Not all of t
| 183 | [What are some tools and techniques for identifying security vulnerabilities in JavaScript code?](#what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code) | Intermediate |
| 184 | [How can you implement secure authentication and authorization in JavaScript applications?](#how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications) | Advanced |
| 185 | [Explain the same-origin policy with regards to JavaScript](#explain-the-same-origin-policy-with-regards-to-javascript) | Intermediate |
| 186 | [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for) | Advanced |
| 186 | [What is `'use strict';` (strict mode) in JavaScript for?](#what-is-use-strict-strict-mode-in-javascript-for) | Advanced |
| 187 | [What tools and techniques do you use for debugging JavaScript code?](#what-tools-and-techniques-do-you-use-for-debugging-javascript-code) | Intermediate |
| 188 | [How does JavaScript garbage collection work?](#how-does-javascript-garbage-collection-work) | Advanced |
| 189 | [Explain what a single page app is and how to make one SEO-friendly](#explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly) | Intermediate |
| 190 | [How can you share code between JavaScript files?](#how-can-you-share-code-between-javascript-files) | Basic |
| 191 | [How do you organize your code?](#how-do-you-organize-your-code) | Intermediate |
| 192 | [What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript) | Advanced |
| 192 | [What are some of the advantages and disadvantages of using TypeScript and compile-to-JavaScript languages](#what-are-some-of-the-advantages-and-disadvantages-of-using-typescript-and-compile-to-javascript-languages) | Advanced |
| 193 | [When would you use `document.write()`?](#when-would-you-use-documentwrite) | Advanced |

<!-- TABLE_OF_CONTENTS:ALL:END -->
Expand Down Expand Up @@ -497,13 +497,13 @@ All of these ways (`<script>`, `<script async>`, and `<script defer>`) are used
- `<script async>` downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. Multiple `<script async>` tags do not wait for each other and execute in no particular order.
- `<script defer>` downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.

Here's a table summarizing the 3 ways of loading `<script>`s in an HTML document.
Here's a table summarizing the 4 ways of loading `<script>`s in an HTML document. Modern apps almost always use modules, which deserve their own row.

| Feature | `<script>` | `<script async>` | `<script defer>` |
| --- | --- | --- | --- |
| Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |
| Execution order | In order of appearance | Not guaranteed | In order of appearance |
| DOM dependency | No | No | Yes (waits for DOM) |
| Feature | `<script>` | `<script async>` | `<script defer>` | `<script type="module">` |
| --- | --- | --- | --- | --- |
| Parsing behavior | Blocks HTML parsing | Downloads in parallel; execution still blocks parsing | Downloads in parallel; execution deferred until after parsing | Downloads in parallel; execution deferred until after parsing |
| Execution order | In order of appearance | Not guaranteed | In order of appearance | In order of appearance, with each script's `import` dependencies resolved first |
| DOM dependency | No | No | Yes (waits for DOM) | Yes (waits for DOM) |

<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->

Expand Down Expand Up @@ -1077,7 +1077,7 @@ The main difference lies in the bubbling behavior of `mouseenter` and `mouseover

<br>

### What is `'use strict';` in JavaScript for?
### What is `'use strict';` (strict mode) in JavaScript for?

<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->

Expand Down Expand Up @@ -4982,13 +4982,13 @@ All of these ways (`<script>`, `<script async>`, and `<script defer>`) are used
- `<script async>` downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. Multiple `<script async>` tags do not wait for each other and execute in no particular order.
- `<script defer>` downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.

Here's a table summarizing the 3 ways of loading `<script>`s in an HTML document.
Here's a table summarizing the 4 ways of loading `<script>`s in an HTML document. Modern apps almost always use modules, which deserve their own row.

| Feature | `<script>` | `<script async>` | `<script defer>` |
| --- | --- | --- | --- |
| Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |
| Execution order | In order of appearance | Not guaranteed | In order of appearance |
| DOM dependency | No | No | Yes (waits for DOM) |
| Feature | `<script>` | `<script async>` | `<script defer>` | `<script type="module">` |
| --- | --- | --- | --- | --- |
| Parsing behavior | Blocks HTML parsing | Downloads in parallel; execution still blocks parsing | Downloads in parallel; execution deferred until after parsing | Downloads in parallel; execution deferred until after parsing |
| Execution order | In order of appearance | Not guaranteed | In order of appearance | In order of appearance, with each script's `import` dependencies resolved first |
| DOM dependency | No | No | Yes (waits for DOM) | Yes (waits for DOM) |

<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->

Expand Down Expand Up @@ -6979,7 +6979,7 @@ The same-origin policy is a security measure implemented in web browsers to prev

<br>

### What is `'use strict';` in JavaScript for?
### What is `'use strict';` (strict mode) in JavaScript for?

<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->

Expand Down Expand Up @@ -7140,11 +7140,11 @@ I organize my code by following a modular approach, using a clear folder structu

<br>

### What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
### What are some of the advantages and disadvantages of using TypeScript and compile-to-JavaScript languages

<!-- Update here: /questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx -->

Using languages that compile to JavaScript, like TypeScript or CoffeeScript, can offer several advantages such as improved syntax, type safety, and better tooling. However, they also come with disadvantages like added build steps, potential performance overhead, and the need to learn new syntax.
Using languages that compile to JavaScript (most commonly TypeScript today, but historically also CoffeeScript, ReScript, Elm, and ClojureScript) can offer several advantages such as improved syntax, type safety, and better tooling. However, they also come with disadvantages like added build steps, potential performance overhead, and the need to learn new syntax.

Advantages:

Expand Down Expand Up @@ -7377,7 +7377,7 @@ JavaScript interview questions categorized by difficulty.

<!-- QUESTIONS:ADVANCED:START -->

1. [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for)
1. [What is `'use strict';` (strict mode) in JavaScript for?](#what-is-use-strict-strict-mode-in-javascript-for)
2. [What are JavaScript polyfills for?](#what-are-javascript-polyfills-for)
3. [What are iterators and generators in JavaScript and what are they used for?](#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for)
4. [What are server-sent events?](#what-are-server-sent-events)
Expand All @@ -7393,7 +7393,7 @@ JavaScript interview questions categorized by difficulty.
14. [How do you validate form elements using the Constraint Validation API?](#how-do-you-validate-form-elements-using-the-constraint-validation-api)
15. [How does hoisting affect function declarations and expressions?](#how-does-hoisting-affect-function-declarations-and-expressions)
16. [What are mocks and stubs and how are they used in testing?](#what-are-mocks-and-stubs-and-how-are-they-used-in-testing)
17. [What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript)
17. [What are some of the advantages and disadvantages of using TypeScript and compile-to-JavaScript languages](#what-are-some-of-the-advantages-and-disadvantages-of-using-typescript-and-compile-to-javascript-languages)
18. [What are some techniques for reducing reflows and repaints?](#what-are-some-techniques-for-reducing-reflows-and-repaints)
19. [What are some tools that can be used to measure and analyze JavaScript performance?](#what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance)
20. [What are Web Workers and how can they be used to improve performance?](#what-are-web-workers-and-how-can-they-be-used-to-improve-performance)
Expand Down
102 changes: 97 additions & 5 deletions questions/describe-event-capturing/en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,105 @@ child.addEventListener('click', () => {

As a result of stopping event propagation, only the `parent` event listener will be called when you click the "Click me!" button, and the `child` event listener will never be called because event propagation has stopped at the `parent` element.

## Uses of event capturing
## Predict the output: capture, target, bubble in order

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.
The complete event flow is the part candidates most often get wrong. The same `click` event passes through every ancestor on the way down (capture), arrives at the target, then walks back up (bubble). Here is the full sequence in one runnable example:

- **Stopping event bubbling:** Imagine you have a nested element (like a button) inside a container element. Clicking the button might also trigger a click event on the container. By enabling event capturing on the container's event listener, you can capture the click event there and prevent it from traveling down to the button, potentially causing unintended behavior.
- **Custom dropdown menus:** When building custom dropdown menus, you might want to capture clicks outside the menu element to close the menu. Using `capture: true` on the `document` object allows you to listen for clicks anywhere on the page and close the menu if the click happens outside its boundaries.
- **Efficiency in certain scenarios:** In some situations, event capturing can be slightly more efficient than relying on bubbling. This is because the event doesn't need to propagate through all child elements before reaching the handler. However, the performance difference is usually negligible for most web applications.
```js live
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

live should only be used for those that can be executed. I don't think we have a way to execute stuff that involves the DOM at the moment.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did check all the live code and it all works and this one as well

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we still want to avoid live for the code that involve DOM?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved the query over the chat, so merging it

const grandparent = document.createElement('div');
const parent = document.createElement('div');
const child = document.createElement('button');
grandparent.appendChild(parent);
parent.appendChild(child);
document.body.appendChild(grandparent);

// Capture handlers (third arg = true)
grandparent.addEventListener(
'click',
() => console.log('1. grandparent capture'),
true,
);
parent.addEventListener('click', () => console.log('2. parent capture'), true);

// Target handler (default: bubble phase)
child.addEventListener('click', () => console.log('3. target'));

// Bubble handlers
parent.addEventListener('click', () => console.log('4. parent bubble'));
grandparent.addEventListener('click', () =>
console.log('5. grandparent bubble'),
);

child.click();
// Output (in this exact order):
// 1. grandparent capture
// 2. parent capture
// 3. target
// 4. parent bubble
// 5. grandparent bubble
```

The full picture: events go down, then up. Capture handlers fire from the root toward the target; bubble handlers fire from the target back toward the root. The target's own handler runs in the middle. (Listeners on the target itself fire in registration order regardless of the `capture` argument; the capture/bubble distinction only applies to ancestors.)

## Bubbling vs capturing comparison

| | Capturing | Bubbling |
| --- | --- | --- |
| Phase order | First (down from root) | Last (up to root) |
| `useCapture` argument | `true` (or `{ capture: true }`) | `false` (the default) |
| Default behavior | Off; must opt in | On; every listener bubbles by default |
| Effect of `event.stopPropagation()` | Stops the event before it reaches the target | Stops the event before higher ancestors see it |
| Common use cases | Intercepting non-bubbling events; pre-empting child handlers; analytics | Most click, input, and change handlers; event delegation |

## When to use the capture phase in real apps

In practice, the capture phase is the right tool for three specific situations:

1. **Delegating non-bubbling events.** `focus`, `blur`, `scroll`, and `mouseenter`/`mouseleave` do not bubble, but they are visible to ancestors during the capture phase. Adding `addEventListener('focus', handler, true)` to a form gives you a delegated focus listener for every input inside it.

```js
form.addEventListener(
'focus',
(event) => {
highlightField(event.target);
},
true, // capture: catches focus events before they stop at the input
);
```

2. **Pre-empting child handlers** for analytics or feature gates. The capture phase runs before any child's bubble handler, so a region-wide "intercept clicks" listener can record the click (or block the action with `stopPropagation()`) before component code sees it.

3. **Modal libraries that need first-look at clicks.** A modal dialog often listens at the document level with `capture: true` for outside-click dismissal. Using the bubble phase would let inner handlers call `stopPropagation()` and accidentally prevent the modal from closing.

## `stopPropagation()` in capture vs bubble

`stopPropagation()` blocks all subsequent phases, not just the next ancestor.

```js live
const outer = document.createElement('div');
const inner = document.createElement('button');
outer.appendChild(inner);
document.body.appendChild(outer);

outer.addEventListener(
'click',
(event) => {
console.log('outer capture: stopping here');
event.stopPropagation();
},
true,
);
inner.addEventListener('click', () => console.log('inner target'));
outer.addEventListener('click', () => console.log('outer bubble'));

inner.click();
// Output: 'outer capture: stopping here'
// The target handler and bubble handler are both skipped.
```

Calling `stopPropagation()` during the capture phase prevents the target's own handlers and every bubble-phase ancestor from running. This is useful for an "intercept and replace" pattern, but if the target needs to keep working, listen during the bubble phase instead.

There is also `event.stopImmediatePropagation()`, which additionally prevents other listeners on the same element (registered in the same phase) from firing. Use it when multiple scripts add listeners to the same element and only one of them should run.

## Further reading

Expand Down
Loading