Skip to content

Commit ba8ae61

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

File tree

33 files changed

+373
-252
lines changed
  • questions
    • explain-ajax-in-as-much-detail-as-possible
    • explain-function-prototype-bind
    • explain-the-concept-of-a-microtask-queue
    • explain-the-concept-of-the-web-socket-api
    • explain-the-difference-between-mutable-and-immutable-objects
    • explain-the-observer-pattern-and-its-use-cases
    • how-can-you-optimize-dom-manipulation-for-better-performance
    • how-do-currying-and-partial-application-differ-from-each-other
    • how-do-you-abort-a-web-request-using-abortcontrollers
    • how-does-hoisting-affect-function-declarations-and-expressions
    • how-is-promiseall-different-from-promiseallsettled
    • what-are-iterators-and-generators-and-what-are-they-used-for
    • what-are-javascript-object-getters-and-setters-for
    • what-are-javascript-object-property-flags-and-descriptors
    • what-are-javascript-polyfills-for
    • what-are-proxies-in-javascript-used-for
    • what-are-some-techniques-for-reducing-reflows-and-repaints
    • what-are-the-benefits-of-using-currying-and-partial-application
    • what-are-the-common-pitfalls-of-using-the-this-keyword
    • what-are-the-differences-between-xmlhttprequest-and-fetch
    • what-are-the-different-ways-to-make-an-api-call-in-javascript
    • what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks
    • what-is-asyncawait-and-how-does-it-simplify-asynchronous-code
    • what-is-objectpreventextensions-for
    • what-is-objectseal-for
    • what-is-the-decorator-pattern-and-how-is-it-used
    • what-is-the-factory-pattern-and-how-is-it-used
    • 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-use-strict-what-are-the-advantages-and-disadvantages-to-using-it
    • why-is-extending-built-in-javascript-objects-not-a-good-idea

33 files changed

+373
-252
lines changed

README.md

Lines changed: 51 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1190,7 +1190,7 @@ AJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication be
11901190

11911191
**Using `XMLHttpRequest`**
11921192

1193-
```js
1193+
```js live
11941194
let xhr = new XMLHttpRequest();
11951195
xhr.onreadystatechange = function () {
11961196
if (xhr.readyState === XMLHttpRequest.DONE) {
@@ -1207,7 +1207,7 @@ xhr.send();
12071207

12081208
**Using `fetch()`**
12091209

1210-
```js
1210+
```js live
12111211
fetch('https://jsonplaceholder.typicode.com/todos/1')
12121212
.then((response) => {
12131213
if (!response.ok) {
@@ -1290,7 +1290,7 @@ These days `fetch()` is preferred for its cleaner syntax and modern features.
12901290

12911291
`AbortController` is used to cancel ongoing asynchronous operations like fetch requests.
12921292

1293-
```js
1293+
```js live
12941294
const controller = new AbortController();
12951295
const signal = controller.signal;
12961296

@@ -1641,7 +1641,7 @@ In JavaScript, iterators and generators are powerful tools for managing sequence
16411641

16421642
Here's an example of an object implementing the iterator interface.
16431643

1644-
```js
1644+
```js live
16451645
const iterator = {
16461646
current: 0,
16471647
last: 5,
@@ -1663,7 +1663,7 @@ while (!result.done) {
16631663

16641664
**Generators** are a special functions that **can pause execution and resume at a later point**. It uses the `function*` syntax and the `yield` keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the `next()` method on the returned iterator advances the generator to the next `yield` statement, and the value after `yield` becomes the return value of `next()`.
16651665

1666-
```js
1666+
```js live
16671667
function* numberGenerator() {
16681668
let num = 0;
16691669
while (num <= 5) {
@@ -1703,7 +1703,7 @@ Generators are powerful for creating iterators on-demand, especially for infinit
17031703

17041704
**Mutable objects** allow for modification of properties and values after creation, which is the default behavior for most objects.
17051705

1706-
```js
1706+
```js live
17071707
const mutableObject = {
17081708
name: 'John',
17091709
age: 30,
@@ -1718,7 +1718,7 @@ console.log(mutableObject); // Output: { name: 'Jane', age: 30 }
17181718

17191719
**Immutable objects** cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.
17201720

1721-
```js
1721+
```js live
17221722
const immutableObject = Object.freeze({
17231723
name: 'John',
17241724
age: 30,
@@ -2003,7 +2003,7 @@ Getters and setters are defined using the `get` and `set` keywords, respectively
20032003

20042004
Here's a code example demonstrating the use of getters and setters:
20052005

2006-
```js
2006+
```js live
20072007
const person = {
20082008
_name: 'John Doe', // Private property
20092009

@@ -2050,7 +2050,7 @@ In JavaScript, a proxy is an object that acts as an intermediary between an obje
20502050

20512051
Here's a basic example of using a `Proxy` to log every property access:
20522052

2053-
```js
2053+
```js live
20542054
const myObject = {
20552055
name: 'John',
20562056
age: 42,
@@ -2065,11 +2065,13 @@ const handler = {
20652065

20662066
const proxiedObject = new Proxy(myObject, handler);
20672067

2068-
console.log(proxiedObject.name); // 'John'
2068+
console.log(proxiedObject.name);
20692069
// Someone accessed property "name"
2070+
// 'John'
20702071

2071-
console.log(proxiedObject.age); // 42
2072+
console.log(proxiedObject.age);
20722073
// Someone accessed property "age"
2074+
// 42
20732075
```
20742076

20752077
Use cases include:
@@ -2442,7 +2444,7 @@ In JavaScript, a proxy is an object that acts as an intermediary between an obje
24422444

24432445
Here's a basic example of using a `Proxy` to log every property access:
24442446

2445-
```js
2447+
```js live
24462448
const myObject = {
24472449
name: 'John',
24482450
age: 42,
@@ -2457,11 +2459,13 @@ const handler = {
24572459

24582460
const proxiedObject = new Proxy(myObject, handler);
24592461

2460-
console.log(proxiedObject.name); // 'John'
2462+
console.log(proxiedObject.name);
24612463
// Someone accessed property "name"
2464+
// 'John'
24622465

2463-
console.log(proxiedObject.age); // 42
2466+
console.log(proxiedObject.age);
24642467
// Someone accessed property "age"
2468+
// 42
24652469
```
24662470

24672471
Use cases include:
@@ -2536,7 +2540,7 @@ The following behavior summarizes the result of accessing the variables before t
25362540

25372541
Hoisting in JavaScript means that function declarations are moved to the top of their containing scope during the compile phase, making them available throughout the entire scope. This allows you to call a function before it is defined in the code. However, function expressions are not hoisted in the same way. If you try to call a function expression before it is defined, you will get an error because the variable holding the function is hoisted but not its assignment.
25382542

2539-
```js
2543+
```js live
25402544
// Function declaration
25412545
console.log(foo()); // Works fine
25422546
function foo() {
@@ -2912,7 +2916,7 @@ In JavaScript, iterators and generators are powerful tools for managing sequence
29122916

29132917
Here's an example of an object implementing the iterator interface.
29142918

2915-
```js
2919+
```js live
29162920
const iterator = {
29172921
current: 0,
29182922
last: 5,
@@ -2934,7 +2938,7 @@ while (!result.done) {
29342938

29352939
**Generators** are a special functions that **can pause execution and resume at a later point**. It uses the `function*` syntax and the `yield` keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the `next()` method on the returned iterator advances the generator to the next `yield` statement, and the value after `yield` becomes the return value of `next()`.
29362940

2937-
```js
2941+
```js live
29382942
function* numberGenerator() {
29392943
let num = 0;
29402944
while (num <= 5) {
@@ -3512,7 +3516,7 @@ if (obj.hasOwnProperty('key')) {
35123516

35133517
**Mutable objects** allow for modification of properties and values after creation, which is the default behavior for most objects.
35143518

3515-
```js
3519+
```js live
35163520
const mutableObject = {
35173521
name: 'John',
35183522
age: 30,
@@ -3527,7 +3531,7 @@ console.log(mutableObject); // Output: { name: 'Jane', age: 30 }
35273531

35283532
**Immutable objects** cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.
35293533

3530-
```js
3534+
```js live
35313535
const immutableObject = Object.freeze({
35323536
name: 'John',
35333537
age: 30,
@@ -3598,15 +3602,19 @@ console.log(obj); // { name: 'John' }
35983602

35993603
<!-- Update here: /questions/what-is-objectseal-for/en-US.mdx -->
36003604

3601-
`Object.seal()` is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones.
3605+
`Object.seal()` is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones. Doing so will throw errors in strict mode but fail silently in non-strict mode. In the following examples, you can uncomment the 'use strict' comment to see this.
3606+
3607+
```js live
3608+
// 'use strict'
36023609

3603-
```js
36043610
const obj = { name: 'John' };
36053611
Object.seal(obj);
36063612

36073613
obj.name = 'Jane'; // Allowed
3608-
obj.age = 30; // Not allowed
3609-
delete obj.name; // Not allowed
3614+
obj.age = 30; // Not allowed, throws an error in strict mode
3615+
delete obj.name; // Not allowed, throws an error in strict mode
3616+
3617+
console.log(obj); // { name: 'Jane } (unchanged)
36103618
```
36113619

36123620
<!-- Update here: /questions/what-is-objectseal-for/en-US.mdx -->
@@ -3623,7 +3631,7 @@ delete obj.name; // Not allowed
36233631

36243632
`Object.preventExtensions()` is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.
36253633

3626-
```js
3634+
```js live
36273635
const obj = { name: 'John' };
36283636
Object.preventExtensions(obj);
36293637

@@ -3649,7 +3657,7 @@ Getters and setters are defined using the `get` and `set` keywords, respectively
36493657

36503658
Here's a code example demonstrating the use of getters and setters:
36513659

3652-
```js
3660+
```js live
36533661
const person = {
36543662
_name: 'John Doe', // Private property
36553663

@@ -3969,16 +3977,19 @@ Promise.all([promise1, promise2, promise3]).then((values) => {
39693977

39703978
`async/await` is a modern syntax in JavaScript that simplifies working with promises. By using the `async` keyword before a function, you can use the `await` keyword inside that function to pause execution until a promise is resolved. This makes asynchronous code look and behave more like synchronous code, making it easier to read and maintain.
39713979

3972-
```js
3980+
```js live
39733981
async function fetchData() {
39743982
try {
3975-
const response = await fetch('https://api.example.com/data');
3983+
const response = await fetch(
3984+
'https://jsonplaceholder.typicode.com/posts/1',
3985+
);
39763986
const data = await response.json();
39773987
console.log(data);
39783988
} catch (error) {
39793989
console.error('Error fetching data:', error);
39803990
}
39813991
}
3992+
fetchData();
39823993
```
39833994

39843995
<!-- Update here: /questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx -->
@@ -5114,7 +5125,7 @@ AJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication be
51145125

51155126
**Using `XMLHttpRequest`**
51165127

5117-
```js
5128+
```js live
51185129
let xhr = new XMLHttpRequest();
51195130
xhr.onreadystatechange = function () {
51205131
if (xhr.readyState === XMLHttpRequest.DONE) {
@@ -5131,7 +5142,7 @@ xhr.send();
51315142

51325143
**Using `fetch()`**
51335144

5134-
```js
5145+
```js live
51355146
fetch('https://jsonplaceholder.typicode.com/todos/1')
51365147
.then((response) => {
51375148
if (!response.ok) {
@@ -5208,7 +5219,7 @@ These days `fetch()` is preferred for its cleaner syntax and modern features.
52085219

52095220
`AbortController` is used to cancel ongoing asynchronous operations like fetch requests.
52105221

5211-
```js
5222+
```js live
52125223
const controller = new AbortController();
52135224
const signal = controller.signal;
52145225

@@ -5296,13 +5307,15 @@ There are three main types of workers in JavaScript:
52965307

52975308
The WebSocket API provides a way to open a persistent connection between a client and a server, allowing for real-time, two-way communication. Unlike HTTP, which is request-response based, WebSocket enables full-duplex communication, meaning both the client and server can send and receive messages independently. This is particularly useful for applications like chat apps, live updates, and online gaming.
52985309

5299-
```js
5300-
// Example of creating a WebSocket connection
5301-
const socket = new WebSocket('ws://example.com/socket');
5310+
The following example uses Postman's WebSocket echo service to demonstrate how web sockets work.
5311+
5312+
```js live
5313+
// Postman's echo server that will echo back messages you send
5314+
const socket = new WebSocket('wss://ws.postman-echo.com/raw');
53025315

53035316
// Event listener for when the connection is open
53045317
socket.addEventListener('open', function (event) {
5305-
socket.send('Hello Server!');
5318+
socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server
53065319
});
53075320

53085321
// Event listener for when a message is received from the server
@@ -5385,7 +5398,7 @@ To detect if JavaScript is disabled on a page, you can use the `<noscript>` HTML
53855398

53865399
The `Intl` namespace object in JavaScript is used for internationalization purposes. It provides language-sensitive string comparison, number formatting, and date and time formatting. For example, you can use `Intl.DateTimeFormat` to format dates according to a specific locale:
53875400

5388-
```js
5401+
```js live
53895402
const date = new Date();
53905403
const formatter = new Intl.DateTimeFormat('en-US');
53915404
console.log(formatter.format(date)); // Outputs date in 'MM/DD/YYYY' format
@@ -6546,7 +6559,7 @@ The Factory pattern is a design pattern used to create objects without specifyin
65466559

65476560
For example, in JavaScript, you can use a factory function to create different types of objects:
65486561

6549-
```js
6562+
```js live
65506563
function createAnimal(type) {
65516564
if (type === 'dog') {
65526565
return { sound: 'woof' };
@@ -6587,7 +6600,7 @@ The Observer pattern is a design pattern where an object, known as the subject,
65876600

65886601
The Module pattern in JavaScript is a design pattern used to create self-contained modules of code. It helps with encapsulation by allowing you to define private and public members within a module. Private members are not accessible from outside the module, while public members are exposed through a returned object. This pattern helps in organizing code, avoiding global namespace pollution, and maintaining a clean separation of concerns.
65896602

6590-
```js
6603+
```js live
65916604
var myModule = (function () {
65926605
var privateVar = 'I am private';
65936606

@@ -6646,7 +6659,7 @@ The Decorator pattern is a structural design pattern that allows behavior to be
66466659

66476660
For example, if you have a `Car` class and you want to add features like `GPS` or `Sunroof` without modifying the `Car` class itself, you can create decorators for these features.
66486661

6649-
```js
6662+
```js live
66506663
class Car {
66516664
drive() {
66526665
return 'Driving';

questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ AJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication be
88

99
**Using `XMLHttpRequest`**
1010

11-
```js
11+
```js live
1212
let xhr = new XMLHttpRequest();
1313
xhr.onreadystatechange = function () {
1414
if (xhr.readyState === XMLHttpRequest.DONE) {
@@ -25,7 +25,7 @@ xhr.send();
2525

2626
**Using `fetch()`**
2727

28-
```js
28+
```js live
2929
fetch('https://jsonplaceholder.typicode.com/todos/1')
3030
.then((response) => {
3131
if (!response.ok) {
@@ -49,7 +49,7 @@ Traditionally, AJAX was implemented using the `XMLHttpRequest` API, but the `fet
4949

5050
Here's a basic example of how it can be used:
5151

52-
```js
52+
```js live
5353
let xhr = new XMLHttpRequest();
5454
xhr.onreadystatechange = function () {
5555
if (xhr.readyState === XMLHttpRequest.DONE) {
@@ -70,7 +70,7 @@ Alternatively, the `fetch()` API provides a modern, promise-based approach to ma
7070

7171
Here's how you can use it:
7272

73-
```js
73+
```js live
7474
fetch('https://jsonplaceholder.typicode.com/todos/1')
7575
.then((response) => {
7676
if (!response.ok) {
@@ -100,8 +100,8 @@ In modern browsers, AJAX is done using the `fetch()` API instead of `XMLHTTPRequ
100100
2. **Return a promise**: The `fetch()` function returns a `Promise` that resolves to a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object representing the response from the server. This `Promise needs` to be handled using `.then()` or `async/await`.
101101
3. **Handling the response**: The `Response` object provides methods to define how the body content should be handled, such as `.json()` for parsing JSON data, `.text()` for plain text, `.blob()` for binary data, etc.
102102

103-
```js
104-
fetch('https://api.example.com/data')
103+
```js live
104+
fetch('https://jsonplaceholder.typicode.com/todos/1')
105105
.then((response) => response.json())
106106
.then((data) => console.log(data))
107107
.catch((error) => console.error('Error:', error));

0 commit comments

Comments
 (0)