Skip to content

Executable coding blocks production-readiness - PR 6 #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 25 commits into from
Mar 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
fdfa1bd
exec: explain-the-concept-of-the-strategy-pattern
tahachm Mar 23, 2025
e7f72be
exec: what-is-the-command-pattern-and-how-is-it-used
tahachm Mar 23, 2025
72d49ae
exec: explain-the-concept-of-partial-application
tahachm Mar 23, 2025
e2855a6
exec: explain-the-concept-of-error-propagation-in-javascript
tahachm Mar 23, 2025
97010c7
exec: what-is-the-difference-between-the-window-object-and-the-docume…
tahachm Mar 23, 2025
0e32451
exec: whats-a-typical-use-case-for-anonymous-functions
tahachm Mar 23, 2025
8f3e866
exec: what-is-the-difference-between-settimeout-setimmediate-and-proc…
tahachm Mar 23, 2025
8aa7364
exec: explain-the-concept-of-tagged-templates
tahachm Mar 23, 2025
eb35746
exec: why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a…
tahachm Mar 23, 2025
1cd44f5
exec: explain-the-concept-of-debouncing-and-throttling
tahachm Mar 23, 2025
2042045
exec: how-do-you-convert-a-set-to-an-array-in-javascript
tahachm Mar 23, 2025
723bcbc
exec: provide-some-examples-of-how-currying-and-partial-application-c…
tahachm Mar 23, 2025
d2d5390
fix: what-are-the-various-data-types-in-javascript
tahachm Mar 23, 2025
7377ba7
exec: explain-the-different-ways-the-this-keyword-can-be-bound
tahachm Mar 23, 2025
7644777
exec: explain-the-difference-between-synchronous-and-asynchronous-fun…
tahachm Mar 23, 2025
69bcf85
exec: explain-the-concept-of-a-callback-function-in-asynchronous-oper…
tahachm Mar 23, 2025
1cdde36
exec: what-are-promises-and-how-do-they-work
tahachm Mar 23, 2025
d86ba17
exec: what-is-the-use-of-promiseall
tahachm Mar 23, 2025
4981d76
exec: how-do-you-handle-errors-in-asynchronous-operations
tahachm Mar 23, 2025
ab5c207
exec: describe-event-bubbling
tahachm Mar 23, 2025
5eca268
fix: describe-the-difference-between-a-cookie-sessionstorage-and-loca…
tahachm Mar 23, 2025
bc5d900
exec: how-do-you-add-remove-and-modify-html-elements-using-javascript
tahachm Mar 23, 2025
16db92b
exec: explain-how-this-works-in-javascript
tahachm Mar 23, 2025
7d2b095
fix: what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-…
tahachm Mar 23, 2025
f50e3c5
fix: how-do-you-get-the-query-string-values-of-the-current-page-in-ja…
tahachm Mar 23, 2025
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
36 changes: 33 additions & 3 deletions questions/describe-event-bubbling/en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ During the bubbling phase, the event starts at the target element and bubbles up

Here's an example using modern ES6 syntax to demonstrate event bubbling:

```js
```js live
// HTML:
// <div id="parent">
// <button id="child">Click me!</button>
// </div>
const parentDiv = document.createElement('div');
parentDiv.id = 'parent';
const button = document.createElement('button');
button.id = 'child';
parentDiv.appendChild(button);
document.body.appendChild(parentDiv);

const parent = document.getElementById('parent');
const child = document.getElementById('child');
Expand All @@ -38,6 +44,9 @@ parent.addEventListener('click', () => {
child.addEventListener('click', () => {
console.log('Child element clicked');
});

// Simulate clicking the button:
child.click();
```

When you click the "Click me!" button, both the child and parent event handlers will be triggered due to the event bubbling.
Expand All @@ -46,11 +55,32 @@ When you click the "Click me!" button, both the child and parent event handlers

Event bubbling can be stopped during the bubbling phase using the `stopPropagation()` method. If an event handler calls `stopPropagation()`, it prevents the event from further bubbling up the DOM tree, ensuring that only the handlers of the elements up to that point in the hierarchy are executed.

```js
```js live
// HTML:
// <div id="parent">
// <button id="child">Click me!</button>
// </div>
const parentDiv = document.createElement('div');
parentDiv.id = 'parent';
const button = document.createElement('button');
button.id = 'child';
parentDiv.appendChild(button);
document.body.appendChild(parentDiv);

const parent = document.getElementById('parent');
const child = document.getElementById('child');

parent.addEventListener('click', () => {
console.log('Parent element clicked');
});

child.addEventListener('click', (event) => {
console.log('Child element clicked');
event.stopPropagation();
event.stopPropagation(); // Stops propagation to parent
});

// Simulate clicking the button:
child.click();
```

## Event delegation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The CookieStore API is relatively new and may not be supported in all browsers (
- **Access**: Data is accessible within all tabs and windows of the same origin.
- **Security**: All JavaScript on the page have access to values within `localStorage`.

```js live
```js
// Set a value in localStorage.
localStorage.setItem('key', 'value');

Expand All @@ -123,7 +123,7 @@ localStorage.clear();
- **Access**: Data is only accessible within the current tab or window. Different tabs or windows with the same page will have different `sessionStorage` objects.
- **Security**: All JavaScript on the same page have access to values within `sessionStorage` for that page.

```js live
```js
// Set a value in sessionStorage.
sessionStorage.setItem('key', 'value');

Expand Down
16 changes: 8 additions & 8 deletions questions/explain-how-this-works-in-javascript/en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ showThis(); // In non-strict mode: Window (global object). In strict mode: undef

When a function is called as a method of an object, `this` refers to the object that the method is called on.

```js
```js live
const obj = {
name: 'John',
showThis: function () {
Expand Down Expand Up @@ -77,7 +77,7 @@ showThisStandalone(); // In non-strict mode: Window (global object). In strict m

When a function is used as a constructor (called with the `new` keyword), `this` refers to the newly-created instance. In the following example, `this` refers to the `Person` object being created, and the `name` property is set on that object.

```js
```js live
function Person(name) {
this.name = name;
}
Expand All @@ -90,7 +90,7 @@ console.log(person.name); // "John"

In ES2015 classes, `this` behaves as it does in object methods. It refers to the instance of the class.

```js
```js live
class Person {
constructor(name) {
this.name = name;
Expand All @@ -114,7 +114,7 @@ You can use `bind()`, `call()`, or `apply()` to explicitly set the value of `thi

Using the `call()` and `apply()` methods allow you to explicitly set the value of `this` when calling the function.

```js
```js live
function showThis() {
console.log(this);
}
Expand All @@ -126,7 +126,7 @@ showThis.apply(obj); // { name: 'John' }

The `bind()` method creates a new function with `this` bound to the specified value.

```js
```js live
function showThis() {
console.log(this);
}
Expand All @@ -142,11 +142,11 @@ Arrow functions do not have their own `this` context. Instead, the `this` is lex

In this example, `this` refers to the global object (window or global), because the arrow function is not bound to the `person` object.

```js
```js live
const person = {
name: 'John',
firstName: 'John',
sayHello: () => {
console.log(`Hello, my name is ${this.name}!`);
console.log(`Hello, my name is ${this.firstName}!`);
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Explain the concept of a callback function in asynchronous operations

A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In asynchronous operations, callbacks are used to handle tasks that take time to complete, such as network requests or file I/O, without blocking the execution of the rest of the code. For example:

```js
```js live
function fetchData(callback) {
setTimeout(() => {
const data = { name: 'John', age: 30 };
Expand Down Expand Up @@ -50,7 +50,7 @@ greet('Alice', sayGoodbye);

### Example of an asynchronous callback

```js
```js live
function fetchData(callback) {
setTimeout(() => {
const data = { name: 'John', age: 30 };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,22 @@ Debouncing and throttling are techniques used to control the rate at which a fun

Debouncing delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.

```js
```js live
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}

const debouncedHello = debounce(() => console.log('Hello world!'), 2000);
debouncedHello(); // Prints 'Hello world!' after 2 seconds
```

Throttling ensures that a function is called at most once in a specified time interval. This is useful for scenarios like window resizing or scrolling where you want to limit the number of times a function is called.

```js
```js live
function throttle(func, limit) {
let inThrottle;
return function (...args) {
Expand All @@ -31,6 +34,17 @@ function throttle(func, limit) {
}
};
}

const handleResize = throttle(() => {
// Update element positions
console.log('Window resized at', new Date().toLocaleTimeString());
}, 2000);

// Simulate rapid calls to handleResize every 100ms
let intervalId = setInterval(() => {
handleResize();
}, 100);
// 'Window resized' is outputted only every 2 seconds due to throttling
```

---
Expand Down Expand Up @@ -77,7 +91,7 @@ Imagine you have a function that updates the position of elements on the screen

#### Code example

```js
```js live
function throttle(func, limit) {
let inThrottle;
return function (...args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Explain the concept of error propagation in JavaScript

Error propagation in JavaScript refers to how errors are passed through the call stack. When an error occurs in a function, it can be caught and handled using `try...catch` blocks. If not caught, the error propagates up the call stack until it is either caught or causes the program to terminate. For example:

```js
```js live
function a() {
throw new Error('An error occurred');
}
Expand Down Expand Up @@ -36,7 +36,7 @@ When an error occurs in a function, it can either be caught and handled within t

To handle errors and prevent them from propagating further, you can use `try...catch` blocks. Here is an example:

```js
```js live
function a() {
throw new Error('An error occurred');
}
Expand All @@ -58,7 +58,7 @@ In this example, the error thrown in function `a` propagates to function `b`, an

Error propagation works differently with asynchronous code, such as promises and `async/await`. For promises, you can use `.catch()` to handle errors:

```js
```js live
function a() {
return Promise.reject(new Error('An error occurred'));
}
Expand All @@ -74,7 +74,7 @@ b().catch((e) => {

For `async/await`, you can use `try...catch` blocks:

```js
```js live
async function a() {
throw new Error('An error occurred');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Explain the concept of partial application

Partial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function `add(a, b)`, you can partially apply it to create a new function `add5` that always adds 5 to its argument.

```js
```js live
function add(a, b) {
return a + b;
}
Expand Down
6 changes: 3 additions & 3 deletions questions/explain-the-concept-of-tagged-templates/en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Explain the concept of tagged templates

Tagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template. For example:

```js
```js live
function tag(strings, ...values) {
return strings[0] + values[0] + strings[1] + values[1] + strings[2];
}
Expand Down Expand Up @@ -44,7 +44,7 @@ When a tagged template is invoked, the tag function receives:

For example:

```js
```js live
function tag(strings, ...values) {
console.log(strings); // ["Hello ", "! How are ", "?"]
console.log(values); // ["world", "you"]
Expand All @@ -65,7 +65,7 @@ Tagged templates can be used for various purposes, such as:

Here is a simple example of a tagged template that escapes HTML:

```js
```js live
function escapeHTML(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i - 1];
Expand Down
12 changes: 7 additions & 5 deletions questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Explain the concept of the Strategy pattern

The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.

```js
```js live
class Context {
constructor(strategy) {
this.strategy = strategy;
Expand All @@ -20,18 +20,20 @@ class Context {
class ConcreteStrategyA {
doAlgorithm(data) {
// Implementation of algorithm A
return 'Algorithm A was run on ' + data;
}
}

class ConcreteStrategyB {
doAlgorithm(data) {
// Implementation of algorithm B
return 'Algorithm B was run on ' + data;
}
}

// Usage
const context = new Context(new ConcreteStrategyA());
context.executeStrategy(data);
context.executeStrategy('someData'); // Output: Algorithm A was run on someData
```

---
Expand All @@ -52,7 +54,7 @@ The Strategy pattern is a behavioral design pattern that enables selecting an al

Consider a scenario where you have different sorting algorithms and you want to switch between them without changing the client code.

```js
```js live
// Strategy interface
class Strategy {
doAlgorithm(data) {
Expand Down Expand Up @@ -92,10 +94,10 @@ class Context {
// Usage
const data = [3, 1, 4, 1, 5, 9];
const context = new Context(new ConcreteStrategyA());
console.log(context.executeStrategy(data)); // Output: [1, 1, 3, 4, 5, 9]
console.log(context.executeStrategy([...data])); // Output: [1, 1, 3, 4, 5, 9]

context.setStrategy(new ConcreteStrategyB());
console.log(context.executeStrategy(data)); // Output: [9, 5, 4, 3, 1, 1]
console.log(context.executeStrategy([...data])); // Output: [9, 5, 4, 3, 1, 1]
```

### Benefits
Expand Down
Loading
Loading