Skip to content

Commit 2cfc234

Browse files
Executable coding blocks production-readiness - PR 4 (#24)
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
1 parent 71db9f8 commit 2cfc234

File tree

11 files changed

+116
-57
lines changed
  • questions
    • can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions
    • explain-hoisting
    • explain-the-concept-of-this-binding-in-event-handlers
    • how-do-you-make-an-http-request-using-the-fetch-api
    • what-are-callback-functions-and-how-are-they-used
    • what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue
    • what-is-objectfreeze-for
    • what-is-the-definition-of-a-higher-order-function
    • what-is-the-dom-and-how-is-it-structured

11 files changed

+116
-57
lines changed

README.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3578,10 +3578,12 @@ const { name, age } = { name: 'John', age: 30 };
35783578

35793579
`Object.freeze()` is used to make an object immutable. Once an object is frozen, you cannot add, remove, or modify its properties. This is useful for creating constants or ensuring that an object remains unchanged throughout the program.
35803580

3581-
```js
3581+
```js live
35823582
const obj = { name: 'John' };
35833583
Object.freeze(obj);
35843584
obj.name = 'Doe'; // This will not change the name property
3585+
3586+
console.log(obj); // { name: 'John' }
35853587
```
35863588

35873589
<!-- Update here: /questions/what-is-objectfreeze-for/en-US.mdx -->
@@ -5056,22 +5058,26 @@ Here's a table summarizing the 3 client storage mechanisms.
50565058

50575059
To make an HTTP request using the Fetch API, you can use the `fetch` function, which returns a promise. You can handle the response using `.then()` and `.catch()` for error handling. Here's a basic example of a GET request:
50585060

5059-
```js
5060-
fetch('https://api.example.com/data')
5061+
```js live
5062+
fetch('https://jsonplaceholder.typicode.com/todos/1')
50615063
.then((response) => response.json())
50625064
.then((data) => console.log(data))
50635065
.catch((error) => console.error('Error:', error));
50645066
```
50655067

50665068
For a POST request, you can pass an options object as the second argument to `fetch`:
50675069

5068-
```js
5069-
fetch('https://api.example.com/data', {
5070+
```js live
5071+
fetch('https://jsonplaceholder.typicode.com/posts', {
50705072
method: 'POST',
5073+
body: JSON.stringify({
5074+
title: 'foo',
5075+
body: 'bar',
5076+
userId: 1,
5077+
}),
50715078
headers: {
5072-
'Content-Type': 'application/json',
5079+
'Content-Type': 'application/json; charset=UTF-8',
50735080
},
5074-
body: JSON.stringify({ key: 'value' }),
50755081
})
50765082
.then((response) => response.json())
50775083
.then((data) => console.log(data))

questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,23 @@ console.log(doubled); // [2, 4, 6, 8, 10]
7676

7777
Arrow functions can be used in event handlers to maintain the `this` context of the class or object.
7878

79-
```js
79+
```js live
8080
class Button {
8181
constructor() {
8282
this.count = 0;
8383
this.button = document.createElement('button');
8484
this.button.innerText = 'Click me';
8585
this.button.addEventListener('click', () => {
8686
this.count++;
87-
console.log(this.count);
87+
console.log('count:', this.count);
8888
});
8989
document.body.appendChild(this.button);
9090
}
9191
}
9292

93-
const button = new Button();
93+
const myButton = new Button();
94+
myButton.button.click(); // count: 1
95+
myButton.button.click(); // count: 2
9496
```
9597

9698
## Further reading

questions/explain-hoisting/en-US.mdx

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ Let's explain with a few code samples. Note that the code for these examples sho
4141

4242
Hoisting is seen in action here as even though `foo` is declared and initialized after the first `console.log()`, the first `console.log()` prints the value of `foo` as `undefined`.
4343

44-
```js
44+
```js live
4545
console.log(foo); // undefined
4646
var foo = 1;
4747
console.log(foo); // 1
4848
```
4949

5050
You can visualize the code as:
5151

52-
```js
52+
```js live
5353
var foo;
5454
console.log(foo); // undefined
5555
foo = 1;
@@ -60,17 +60,17 @@ console.log(foo); // 1
6060

6161
Variables declared via `let`, `const`, and `class` are hoisted as well. However, unlike `var` and `function`, they are not initialized and accessing them before the declaration will result in a `ReferenceError` exception. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
6262

63-
```js
63+
```js live
6464
y; // ReferenceError: Cannot access 'y' before initialization
6565
let y = 'local';
6666
```
6767

68-
```js
68+
```js live
6969
z; // ReferenceError: Cannot access 'z' before initialization
7070
const z = 'local';
7171
```
7272

73-
```js
73+
```js live
7474
Foo; // ReferenceError: Cannot access 'Foo' before initialization
7575

7676
class Foo {
@@ -82,7 +82,7 @@ class Foo {
8282

8383
Function expressions are functions written in the form of variable declarations. Since they are also declared using `var`, only the variable declaration is hoisted.
8484

85-
```js
85+
```js live
8686
console.log(bar); // undefined
8787
bar(); // Uncaught TypeError: bar is not a function
8888

@@ -95,7 +95,7 @@ var bar = function () {
9595

9696
Function declarations use the `function` keyword. Unlike function expressions, function declarations have both the declaration and definition hoisted, thus they can be called even before they are declared.
9797

98-
```js
98+
```js live
9999
console.log(foo); // [Function: foo]
100100
foo(); // 'FOOOOO'
101101

questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,17 @@ In JavaScript, the `this` keyword is a reference to the object that is currently
1818

1919
In the context of event handlers, `this` usually refers to the DOM element that triggered the event. For example:
2020

21-
```js
21+
```js live
22+
// Create a button element and append it to the DOM
23+
const button = document.createElement('button');
24+
button.id = 'myButton';
25+
document.body.appendChild(button);
26+
2227
document.getElementById('myButton').addEventListener('click', function () {
23-
console.log(this); // Logs the button element
28+
console.log(this); // `this` refers to the 'myButton' element
2429
});
30+
31+
button.click(); // Logs the button element
2532
```
2633

2734
In this example, `this` inside the event handler refers to the button element that was clicked.
@@ -34,7 +41,12 @@ There are several ways to change the value of `this` in event handlers:
3441

3542
The `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value:
3643

37-
```js
44+
```js live
45+
// Create a button element and append it to the DOM
46+
const button = document.createElement('button');
47+
button.id = 'myButton';
48+
document.body.appendChild(button);
49+
3850
function handleClick() {
3951
console.log(this); // Logs the object passed to bind()
4052
}
@@ -43,6 +55,8 @@ const obj = { name: 'MyObject' };
4355
document
4456
.getElementById('myButton')
4557
.addEventListener('click', handleClick.bind(obj));
58+
59+
button.click(); // Logs obj because handleClick was bound to obj using bind()
4660
```
4761

4862
In this example, `this` inside `handleClick` refers to `obj`.
@@ -51,7 +65,12 @@ In this example, `this` inside `handleClick` refers to `obj`.
5165

5266
Arrow functions do not have their own `this` context; they inherit `this` from the surrounding lexical context:
5367

54-
```js
68+
```js live
69+
// Create a button element and append it to the DOM
70+
const button = document.createElement('button');
71+
button.id = 'myButton';
72+
document.body.appendChild(button);
73+
5574
const obj = {
5675
name: 'MyObject',
5776
handleClick: function () {
@@ -62,6 +81,7 @@ const obj = {
6281
};
6382

6483
obj.handleClick();
84+
button.click(); // This will log obj
6585
```
6686

6787
In this example, `this` inside the arrow function refers to `obj`.
@@ -70,7 +90,12 @@ In this example, `this` inside the arrow function refers to `obj`.
7090

7191
You can also assign the context explicitly by using a variable:
7292

73-
```js
93+
```js live
94+
// Create a button element and append it to the DOM
95+
const button = document.createElement('button');
96+
button.id = 'myButton';
97+
document.body.appendChild(button);
98+
7499
const obj = {
75100
name: 'MyObject',
76101
handleClick: function () {
@@ -82,6 +107,7 @@ const obj = {
82107
};
83108

84109
obj.handleClick();
110+
button.click(); // This will log obj
85111
```
86112

87113
In this example, `self` is used to capture the value of `this` from the outer function.

questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ function example() {
5656
// Now use a and b
5757
console.log(a + b);
5858
}
59-
example();
59+
example(); // Output: 3
6060
```
6161

6262
### Declare functions before calling them

questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,26 @@ title: How do you make an HTTP request using the Fetch API?
66

77
To make an HTTP request using the Fetch API, you can use the `fetch` function, which returns a promise. You can handle the response using `.then()` and `.catch()` for error handling. Here's a basic example of a GET request:
88

9-
```js
10-
fetch('https://api.example.com/data')
9+
```js live
10+
fetch('https://jsonplaceholder.typicode.com/todos/1')
1111
.then((response) => response.json())
1212
.then((data) => console.log(data))
1313
.catch((error) => console.error('Error:', error));
1414
```
1515

1616
For a POST request, you can pass an options object as the second argument to `fetch`:
1717

18-
```js
19-
fetch('https://api.example.com/data', {
18+
```js live
19+
fetch('https://jsonplaceholder.typicode.com/posts', {
2020
method: 'POST',
21+
body: JSON.stringify({
22+
title: 'foo',
23+
body: 'bar',
24+
userId: 1,
25+
}),
2126
headers: {
22-
'Content-Type': 'application/json',
27+
'Content-Type': 'application/json; charset=UTF-8',
2328
},
24-
body: JSON.stringify({ key: 'value' }),
2529
})
2630
.then((response) => response.json())
2731
.then((data) => console.log(data))
@@ -36,8 +40,8 @@ fetch('https://api.example.com/data', {
3640

3741
To make a basic GET request, you can use the `fetch` function with the URL of the resource you want to fetch. The `fetch` function returns a promise that resolves to the `Response` object representing the response to the request.
3842

39-
```js
40-
fetch('https://api.example.com/data')
43+
```js live
44+
fetch('https://jsonplaceholder.typicode.com/todos/1')
4145
.then((response) => {
4246
if (!response.ok) {
4347
throw new Error('Network response was not ok');
@@ -52,8 +56,8 @@ fetch('https://api.example.com/data')
5256

5357
The `Response` object has several methods to handle different types of responses, such as `.json()`, `.text()`, `.blob()`, and `.arrayBuffer()`.
5458

55-
```js
56-
fetch('https://api.example.com/data')
59+
```js live
60+
fetch('https://jsonplaceholder.typicode.com/todos/1')
5761
.then((response) => response.text())
5862
.then((text) => console.log(text))
5963
.catch((error) => console.error('Error:', error));
@@ -63,13 +67,17 @@ fetch('https://api.example.com/data')
6367

6468
To make a POST request, you need to pass an options object as the second argument to `fetch`. This object can include the HTTP method, headers, and body of the request.
6569

66-
```js
67-
fetch('https://api.example.com/data', {
70+
```js live
71+
fetch('https://jsonplaceholder.typicode.com/posts', {
6872
method: 'POST',
73+
body: JSON.stringify({
74+
title: 'foo',
75+
body: 'bar',
76+
userId: 1,
77+
}),
6978
headers: {
70-
'Content-Type': 'application/json',
79+
'Content-Type': 'application/json; charset=UTF-8',
7180
},
72-
body: JSON.stringify({ key: 'value' }),
7381
})
7482
.then((response) => {
7583
if (!response.ok) {
@@ -85,8 +93,8 @@ fetch('https://api.example.com/data', {
8593

8694
Error handling in the Fetch API can be done using the `.catch()` method. It's also a good practice to check the `response.ok` property to ensure the request was successful.
8795

88-
```js
89-
fetch('https://api.example.com/data')
96+
```js live
97+
fetch('https://jsonplaceholder.tyicode.com/posts/1/comments') // Typo in the URL
9098
.then((response) => {
9199
if (!response.ok) {
92100
throw new Error('Network response was not ok');
@@ -101,10 +109,12 @@ fetch('https://api.example.com/data')
101109

102110
You can also use the Fetch API with `async/await` for a more synchronous-looking code.
103111

104-
```js
112+
```js live
105113
async function fetchData() {
106114
try {
107-
const response = await fetch('https://api.example.com/data');
115+
const response = await fetch(
116+
'https://jsonplaceholder.typicode.com/todos/1',
117+
);
108118
if (!response.ok) {
109119
throw new Error('Network response was not ok');
110120
}

questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ greet('Alice', sayGoodbye);
5252

5353
Asynchronous callbacks are used for operations that take some time to complete, such as reading files, making HTTP requests, or handling events. These callbacks are executed after the asynchronous operation has finished.
5454

55-
```js
55+
```js live
5656
function fetchData(callback) {
5757
setTimeout(() => {
5858
const data = { name: 'John Doe' };
@@ -65,6 +65,7 @@ function handleData(data) {
6565
}
6666

6767
fetchData(handleData);
68+
// Output: { name: 'John Doe' } after 1 second
6869
```
6970

7071
### Common use cases
@@ -73,19 +74,25 @@ fetchData(handleData);
7374

7475
Callbacks are often used in event handling. For example, in JavaScript, you can pass a callback function to an event listener.
7576

76-
```js
77-
document.getElementById('myButton').addEventListener('click', function () {
78-
console.log('Button clicked!');
77+
```js live
78+
const button = document.createElement('button');
79+
80+
button.addEventListener('click', () => {
81+
setTimeout(() => {
82+
console.log('Button clicked after 1s');
83+
}, 1000);
7984
});
85+
86+
button.click();
8087
```
8188

8289
#### API calls
8390

8491
Callbacks are frequently used in making API calls to handle the response data.
8592

86-
```js
93+
```js live
8794
function getUserData(userId, callback) {
88-
fetch(`https://api.example.com/users/${userId}`)
95+
fetch(`https://jsonplaceholder.typicode.com/todos/2`)
8996
.then((response) => response.json())
9097
.then((data) => callback(data))
9198
.catch((error) => console.error('Error:', error));
@@ -102,7 +109,7 @@ getUserData(1, displayUserData);
102109

103110
Callbacks are also used with timers like `setTimeout` and `setInterval`.
104111

105-
```js
112+
```js live
106113
function sayHello() {
107114
console.log('Hello, world!');
108115
}

questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ Microtasks are tasks that have a higher priority than macrotasks and are execute
6767

6868
The following code logs some statements using a combination of normal execution, macrotasks, and microtasks.
6969

70-
```js
70+
```js live
7171
console.log('Start');
7272

7373
setTimeout(() => {

0 commit comments

Comments
 (0)