From 3b0f7b65ebf20e778480052c56e51d97ff74a833 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sat, 1 Mar 2025 18:34:36 +0500 Subject: [PATCH 01/56] exec: how-do-you-convert-a-string-to-a-number-in-javascript --- .../en-US.mdx | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx b/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx index 91f6212..c827371 100644 --- a/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx +++ b/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx @@ -14,60 +14,68 @@ In JavaScript, you can convert a string to a number using several methods. The m The `Number()` function converts a string to a number. It can handle both integer and floating-point numbers. -```js +```js live let str = '123'; -let num = Number(str); // 123 +let num = Number(str); +console.log(num); // 123 let floatStr = '123.45'; -let floatNum = Number(floatStr); // 123.45 +let floatNum = Number(floatStr); +console.log(floatNum); // 123.45 ``` ### Using the `parseInt()` function The `parseInt()` function parses a string and returns an integer. It can also take a second argument, the radix (base) of the numeral system to be used. -```js +```js live let str = '123'; -let num = parseInt(str); // 123 +let num = parseInt(str); +console.log(num); // 123 -let floatStr = '123.45'; -let floatNum = parseInt(floatStr); // 123 +let floatStr = '120.45'; +let floatNum = parseInt(floatStr); +console.log(floatNum); // 120 let binaryStr = '1010'; -let binaryNum = parseInt(binaryStr, 2); // 10 +let binaryNum = parseInt(binaryStr, 2); +console.log(binaryNum); // 10 ``` ### Using the `parseFloat()` function The `parseFloat()` function parses a string and returns a floating-point number. -```js +```js live let floatStr = '123.45'; -let floatNum = parseFloat(floatStr); // 123.45 +let floatNum = parseFloat(floatStr); +console.log(floatNum); // 123.45 ``` ### Using the unary plus operator (`+`) The unary plus operator can be used to convert a string to a number. It is a shorthand method and works for both integers and floating-point numbers. -```js +```js live let str = '123'; -let num = +str; // 123 +let num = +str; +console.log(num); // 123 let floatStr = '123.45'; -let floatNum = +floatStr; // 123.45 +let floatNum = +floatStr; +console.log(floatNum); // 123.45 ``` ### Handling non-numeric strings If the string cannot be converted to a number, these methods will return `NaN` (Not-a-Number). -```js +```js live let invalidStr = 'abc'; -let num = Number(invalidStr); // NaN -let intNum = parseInt(invalidStr); // NaN -let floatNum = parseFloat(invalidStr); // NaN -let unaryNum = +invalidStr; // NaN +console.log(Number(invalidStr)); // NaN +console.log(parseInt(invalidStr)); // NaN +console.log(parseFloat(invalidStr)); // NaN +console.log(+invalidStr); // NaN ``` ## Further reading From df35cdd9b90da436f6aa445dbd9c23559ef5461d Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 17:41:50 +0500 Subject: [PATCH 02/56] exec: what-are-the-various-data-types-in-javascript --- .../en-US.mdx | 63 +++++++++++++------ 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/questions/what-are-the-various-data-types-in-javascript/en-US.mdx b/questions/what-are-the-various-data-types-in-javascript/en-US.mdx index 20239d2..2bb952e 100644 --- a/questions/what-are-the-various-data-types-in-javascript/en-US.mdx +++ b/questions/what-are-the-various-data-types-in-javascript/en-US.mdx @@ -38,73 +38,86 @@ JavaScript, like many programming languages, has a variety of data types to repr 1. **Number**: Represents both integer and floating-point numbers. JavaScript only has one type of number. -```js +```js live let age = 25; let price = 99.99; +console.log(price); // 99.99 ``` 2. **String**: Represents sequences of characters. `Strings` can be enclosed in single quotes, double quotes, or backticks (for template literals). -```js -let name = 'John Doe'; +```js live +let myName = 'John Doe'; let greeting = 'Hello, world!'; -let message = `Welcome, ${name}!`; +let message = `Welcome, ${myName}!`; +console.log(message); // "Welcome, John Doe!" ``` 3. **Boolean**: Represents logical entities and can have two values: `true` or `false`. -```js +```js live let isActive = true; let isOver18 = false; +console.log(isOver18); // false ``` 4. **Undefined**: A variable that has been declared but not assigned a value is of type `undefined`. -```js +```js live let user; console.log(user); // undefined ``` 5. **Null**: Represents the intentional absence of any object value. It is a primitive value and is treated as a falsy value. -```js +```js live let user = null; +console.log(user); // null +if (!user) { + console.log('user is a falsy value'); +} ``` 6. **Symbol**: A unique and immutable `primitive` value, typically used as the key of an object property. -```js +```js live let sym1 = Symbol(); let sym2 = Symbol('description'); +console.log(sym1); // Symbol() +console.log(sym2); // Symbol(description) ``` 7. **BigInt**: Used for representing integers with arbitrary precision, useful for working with very large numbers. -```js +```js live let bigNumber = BigInt(9007199254740991); let anotherBigNumber = 1234567890123456789012345678901234567890n; +console.log(bigNumber); // 9007199254740991n +console.log(anotherBigNumber); // 1234567890123456789012345678901234567890n ``` ### Non-primitive (reference) data types 1. **Object**: It is used to store collections of data and more complex entities. `Objects` are created using curly braces `{}`. -```js +```js live let person = { name: 'Alice', age: 30, }; +console.log(person); // {name: "Alice", age: 30} ``` 2. **Array**: A special type of object used for storing ordered collections of data. `Arrays` are created using square brackets `[]`. -```js +```js live let numbers = [1, 2, 3, 4, 5]; +console.log(numbers); ``` 3. **Function**: `Functions` in JavaScript are `objects`. They can be defined using function declarations or expressions. -```js +```js live function greet() { console.log('Hello!'); } @@ -112,40 +125,47 @@ function greet() { let add = function (a, b) { return a + b; }; + +greet(); // "Hello!" +console.log(add(2, 3)); // 5 ``` 4. **Date**: Represents dates and times. The `Date` object is used to work with dates. -```js +```js live let today = new Date(); +console.log(today); ``` 5. **RegExp**: Represents regular expressions, which are patterns used to match character combinations in strings. -```js +```js live let pattern = /abc/; +console.log(pattern); ``` 6. **Map**: A collection of keyed data items, similar to an `object` but allows keys of any type. -```js +```js live let map = new Map(); map.set('key1', 'value1'); +console.log(map); ``` 7. **Set**: A collection of unique values. -```js +```js live let set = new Set(); set.add(1); set.add(2); +console.log(set); ``` ## Determining data types JavaScript is a dynamically-typed language, which means variables can hold values of different data types over time. The `typeof` operator can be used to determine the data type of a value or variable. -```js +```js live console.log(typeof 42); // "number" console.log(typeof 'hello'); // "string" console.log(typeof true); // "boolean" @@ -164,9 +184,12 @@ console.log(typeof function () {}); // "function" JavaScript often performs type coercion, converting values from one type to another, which can lead to unexpected results. -```js -let result = '5' + 2; // '52' (string concatenation) -let difference = '5' - 2; // 3 (numeric subtraction) +```js live +let result = '5' + 2; +console.log(result, typeof result); // "52 string" (string concatenation) + +let difference = '5' - 2; +console.log(difference, typeof difference); // 3 "number" (numeric subtraction) ``` In the first example, since strings can be concatenated with the `+` operator, the number is converted into a string and the two strings are concatenated together. In the second example, strings cannot work with the minus operator (`-`), but two numbers can be minused, so the string is first converted into a number and the result is the difference. From 8278bc140740fe0f7b47837c3ad6e26947881a94 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 17:52:06 +0500 Subject: [PATCH 03/56] exec: explain-the-concept-of-hoisting-with-regards-to-functions --- .../en-US.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx b/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx index 5ee9f24..2c98bc1 100644 --- a/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx +++ b/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the concept of hoisting with regards to functions Hoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way. -```js +```js live // Function declaration hoistedFunction(); // Works fine function hoistedFunction() { @@ -30,7 +30,7 @@ Hoisting is a JavaScript mechanism where variables and function declarations are Function declarations are fully hoisted. This means you can call a function before its declaration in the code. -```js +```js live hoistedFunction(); // Works fine function hoistedFunction() { @@ -42,7 +42,7 @@ function hoistedFunction() { Function expressions, including arrow functions, are not hoisted in the same way. They are treated as variable assignments and are only hoisted as undefined. -```js +```js live nonHoistedFunction(); // Throws an error: TypeError: nonHoistedFunction is not a function var nonHoistedFunction = function () { @@ -54,7 +54,7 @@ var nonHoistedFunction = function () { Arrow functions behave similarly to function expressions in terms of hoisting. -```js +```js live arrowFunction(); // Throws an error: TypeError: arrowFunction is not a function var arrowFunction = () => { From 66da94024b13c430f8fa958f7f0311cfd39366e2 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 18:01:32 +0500 Subject: [PATCH 04/56] exec: explain-the-difference-in-hoisting-between-var-let-and-const --- .../en-US.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx b/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx index 689919f..31cf4af 100644 --- a/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx +++ b/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx @@ -14,7 +14,7 @@ title: Explain the difference in hoisting between `var`, `let`, and `const` `var` declarations are hoisted to the top of their containing function or global scope. This means the variable is available throughout the entire function or script, even before the line where it is declared. However, the variable is initialized with `undefined` until the actual declaration is encountered. -```js +```js live console.log(a); // Output: undefined var a = 10; console.log(a); // Output: 10 @@ -24,7 +24,7 @@ console.log(a); // Output: 10 `let` declarations are also hoisted to the top of their block scope, but they are not initialized. This creates a "temporal dead zone" (TDZ) from the start of the block until the declaration is encountered. Accessing the variable in the TDZ results in a `ReferenceError`. -```js +```js live console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 20; console.log(b); // Output: 20 @@ -34,7 +34,7 @@ console.log(b); // Output: 20 `const` declarations behave similarly to `let` in terms of hoisting. They are hoisted to the top of their block scope but are not initialized, resulting in a TDZ. Additionally, `const` requires an initial value at the time of declaration and cannot be reassigned. -```js +```js live console.log(c); // ReferenceError: Cannot access 'c' before initialization const c = 30; console.log(c); // Output: 30 From 377fded0cf67ab3f36e63619d55a1d5778e4471a Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 18:51:43 +0500 Subject: [PATCH 05/56] exec: what-is-the-spread-operator-and-how-is-it-used --- .../en-US.mdx | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx b/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx index 5df5754..99e38a6 100644 --- a/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx +++ b/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx @@ -6,14 +6,16 @@ title: What is the spread operator and how is it used? The spread operator, represented by three dots (`...`), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function. -```js +```js live const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; -const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6] +const combined = [...arr1, ...arr2]; +console.log(combined); // [1, 2, 3, 4, 5, 6] const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; -const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 } +const combinedObj = { ...obj1, ...obj2 }; +console.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 } ``` --- @@ -24,60 +26,65 @@ const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 } The spread operator can be used to expand elements of an array into individual elements. This is useful for combining arrays or copying arrays. -```js +```js live const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; -const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6] +const combined = [...arr1, ...arr2]; +console.log(combined); // [1, 2, 3, 4, 5, 6] ``` ### Copying arrays You can create a shallow copy of an array using the spread operator. -```js +```js live const original = [1, 2, 3]; -const copy = [...original]; // [1, 2, 3] +const copy = [...original]; +console.log(copy); // [1, 2, 3] ``` ### Passing array elements as function arguments The spread operator can be used to pass elements of an array as arguments to a function. -```js +```js live function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; -const result = sum(...numbers); // 6 +console.log(sum(...numbers)); // 6 ``` ### Expanding objects The spread operator can also be used to expand properties of an object. This is useful for combining objects or copying objects. -```js +```js live const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; -const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 } +const combinedObj = { ...obj1, ...obj2 }; +console.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 } ``` ### Copying objects You can create a shallow copy of an object using the spread operator. -```js +```js live const originalObj = { a: 1, b: 2 }; -const copyObj = { ...originalObj }; // { a: 1, b: 2 } +const copyObj = { ...originalObj }; +console.log(copyObj); // { a: 1, b: 2 } ``` ### Using with strings The spread operator can also be used to expand a string into individual characters. -```js +```js live const str = 'hello'; -const chars = [...str]; // ['h', 'e', 'l', 'l', 'o'] +const chars = [...str]; +console.log(chars); // ['h', 'e', 'l', 'l', 'o'] ``` ## Further reading From 03d6fcd90fabc97edd05bc861b17514b8c798f5a Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 18:55:21 +0500 Subject: [PATCH 06/56] exec: how-do-you-check-the-data-type-of-a-variable --- .../en-US.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx b/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx index 3a45b34..dc0df87 100644 --- a/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx +++ b/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx @@ -14,7 +14,7 @@ To check the data type of a variable in JavaScript, you can use the `typeof` ope The `typeof` operator is the most common way to check the data type of a variable in JavaScript. It returns a string indicating the type of the operand. -```js +```js live let str = 'Hello, world!'; console.log(typeof str); // "string" @@ -41,7 +41,7 @@ console.log(typeof sym); // "symbol" The `typeof` operator returns `"object"` for `null`, which can be misleading. To specifically check for `null`, you should use a strict equality comparison. -```js +```js live let n = null; console.log(n === null); // true ``` @@ -50,7 +50,7 @@ console.log(n === null); // true Arrays are a special type of object in JavaScript. To check if a variable is an array, you can use the `Array.isArray` method. -```js +```js live let arr = [1, 2, 3]; console.log(Array.isArray(arr)); // true ``` @@ -59,7 +59,7 @@ console.log(Array.isArray(arr)); // true `NaN` (Not-a-Number) is a special numeric value in JavaScript. To check if a value is `NaN`, you can use the `Number.isNaN` method. -```js +```js live let notANumber = NaN; console.log(Number.isNaN(notANumber)); // true ``` @@ -68,7 +68,7 @@ console.log(Number.isNaN(notANumber)); // true To check if a variable is either `null` or `undefined`, you can use a combination of the `==` operator and the `typeof` operator. -```js +```js live let value = null; console.log(value == null); // true From c036438019f93d4b4767b23ea12fd3e3192c75b4 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 19:05:18 +0500 Subject: [PATCH 07/56] exec: what-are-the-differences-between-variables-created-using-let-var-or-const --- .../en-US.mdx | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx b/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx index 6ee515a..7c9df6b 100644 --- a/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx +++ b/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx @@ -24,7 +24,7 @@ Let's look at the difference in behavior between `var`, `let`, and `const`. Variables declared using the `var` keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. `let` and `const` are _block scoped_, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop). -```js +```js live function foo() { // All variables are accessible within functions. var bar = 1; @@ -36,6 +36,7 @@ function foo() { console.log(qux); // 3 } +foo(); // Prints each variable successfully console.log(bar); // ReferenceError: bar is not defined console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined @@ -43,7 +44,7 @@ console.log(qux); // ReferenceError: qux is not defined In the following example, `bar` is accessible outside of the `if` block but `baz` and `quz` are not. -```js +```js live if (true) { var bar = 1; let baz = 2; @@ -61,7 +62,7 @@ console.log(qux); // ReferenceError: qux is not defined `var` and `let` variables can be initialized without a value but `const` declarations must be initialized. -```js +```js live var foo; // Ok let bar; // Ok const baz; // SyntaxError: Missing initializer in const declaration @@ -71,10 +72,10 @@ const baz; // SyntaxError: Missing initializer in const declaration Redeclaring a variable with `var` will not throw an error, but `let` and `const` will. -```js +```js live var foo = 1; -var foo = 2; -console.log(foo); // 2 +var foo = 2; // Ok +console.log(foo); // Should print 2, but SyntaxError from baz prevents the code executing. let baz = 3; let baz = 4; // Uncaught SyntaxError: Identifier 'baz' has already been declared @@ -84,7 +85,7 @@ let baz = 4; // Uncaught SyntaxError: Identifier 'baz' has already been declared `let` and `const` differ in that `var` and `let` allow reassigning the variable's value while `const` does not. -```js +```js live var foo = 1; foo = 2; // This is fine. @@ -99,14 +100,14 @@ baz = 6; // Uncaught TypeError: Assignment to constant variable. `var` ,`let` and `const` declared variables are all hoisted. `var` declared variables are auto-initialized with an `undefined` value. However, `let` and `const` variables are not initialized and accessing them before the declaration will result in a `ReferenceError` exception because they are in a "temporal dead zone" from the start of the block until the declaration is processed. -```js +```js live console.log(foo); // undefined var foo = 'foo'; -console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization +console.log(baz); // ReferenceError: Cannot access 'baz' before initialization let baz = 'baz'; -console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization +console.log(bar); // ReferenceError: Cannot access 'baz' before initialization const bar = 'bar'; ``` From d6f3b0e169a9c55093eb3a7e1d7efdbbece688bd Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 19:19:18 +0500 Subject: [PATCH 08/56] exec: whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states --- .../en-US.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx b/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx index 5bc5d61..d3837ba 100644 --- a/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx +++ b/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx @@ -17,18 +17,18 @@ subtitle: How would you go about checking for any of these states? **Undeclared** variables are created when you assign a value to an identifier that is not previously created using `var`, `let` or `const`. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a `ReferenceError` will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad in the same way that global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a `try`/`catch` block. -```js +```js live function foo() { x = 1; // Throws a ReferenceError in strict mode } foo(); -console.log(x); // 1 +console.log(x); // 1 (if not in strict mode) ``` Using the `typeof` operator on undeclared variables will give `'undefined'`. -```js +```js live console.log(typeof y === 'undefined'); // true ``` @@ -36,7 +36,7 @@ console.log(typeof y === 'undefined'); // true A variable that is `undefined` is a variable that has been declared, but not assigned a value. It is of type `undefined`. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of `undefined`. To check for it, compare using the strict equality (`===`) operator or `typeof` which will give the `'undefined'` string. Note that you should not be using the loose equality operator (`==`) to check, as it will also return `true` if the value is `null`. -```js +```js live let foo; console.log(foo); // undefined console.log(foo === undefined); // true @@ -53,7 +53,7 @@ console.log(baz); // undefined A variable that is `null` will have been explicitly assigned to the `null` value. It represents no value and is different from `undefined` in the sense that it has been explicitly assigned. To check for `null,` simply compare using the strict equality operator. Note that like the above, you should not be using the loose equality operator (`==`) to check, as it will also return `true` if the value is `undefined`. -```js +```js live const foo = null; console.log(foo === null); // true console.log(typeof foo === 'object'); // true From 15d0f04ac8c65a566899450aba96972a26ff9604 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 19:29:15 +0500 Subject: [PATCH 09/56] exec: what-are-template-literals-and-how-are-they-used --- .../en-US.mdx | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx b/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx index f5a786d..4deffb2 100644 --- a/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx +++ b/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx @@ -8,9 +8,9 @@ Template literals are a feature in JavaScript that allow for easier string inter Example: -```js -const name = 'John'; -const greeting = `Hello, ${name}!`; +```js live +const myName = 'John'; +const greeting = `Hello, ${myName}!`; console.log(greeting); // Output: Hello, John! ``` @@ -32,10 +32,10 @@ One of the most powerful features of template literals is string interpolation. Example: -```js -const name = 'John'; +```js live +const myName = 'John'; const age = 30; -const greeting = `Hello, my name is ${name} and I am ${age} years old.`; +const greeting = `Hello, my name is ${myName} and I am ${age} years old.`; console.log(greeting); // Output: Hello, my name is John and I am 30 years old. ``` @@ -45,7 +45,7 @@ Template literals make it easy to create multi-line strings without the need for Example: -```js +```js live const multiLineString = `This is a string that spans multiple lines.`; @@ -62,16 +62,16 @@ Tagged templates allow you to parse template literals with a function. The funct Example: -```js +```js live function tag(strings, ...values) { - console.log(strings); // Array of string literals - console.log(values); // Array of values - return 'Tagged template result'; + console.log(strings); // Array of string literals: ["Hello, ", "!"] + console.log(values); // Array of values: ["John"] + return 'Custom tagged template result'; } -const name = 'John'; -const result = tag`Hello, ${name}!`; -console.log(result); // Output: Tagged template result +const myName = 'John'; +const result = tag`Hello, ${myName}!`; +console.log(result); // Output: Custom tagged template result ``` ### Nesting template literals @@ -80,10 +80,10 @@ You can nest template literals within each other for more complex string constru Example: -```js -const name = 'John'; +```js live +const myName = 'John'; const age = 30; -const nestedTemplate = `Name: ${name}, Age: ${age}, Info: ${`Name: ${name}, Age: ${age}`}`; +const nestedTemplate = `Name: ${myName}, Age: ${age}, Info: ${`Name: ${myName}, Age: ${age}`}`; console.log(nestedTemplate); // Output: Name: John, Age: 30, Info: Name: John, Age: 30 ``` From e3f2fe4009eded4ac3c758d28ff4f77a60f0a870 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 19:48:33 +0500 Subject: [PATCH 10/56] exec: how-can-you-avoid-problems-related-to-hoisting --- .../en-US.mdx | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx b/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx index b31b9a2..f6ea850 100644 --- a/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx +++ b/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx @@ -6,16 +6,17 @@ title: How can you avoid problems related to hoisting? To avoid problems related to hoisting, always declare variables at the top of their scope using `let` or `const` instead of `var`. This ensures that variables are block-scoped and not hoisted to the top of their containing function or global scope. Additionally, declare functions before they are called to avoid issues with function hoisting. -```js +```js live // Use let or const let x = 10; const y = 20; +console.log(x, y); // Output: 10 20 // Declare functions before calling them function myFunction() { console.log('Hello, world!'); } -myFunction(); +myFunction(); // Output: 'Hello, world!' ``` --- @@ -30,7 +31,11 @@ Hoisting is JavaScript's default behavior of moving declarations to the top of t `let` and `const` are block-scoped, meaning they are only accessible within the block they are defined. This prevents them from being hoisted to the top of the function or global scope, reducing the risk of unexpected behavior. -```js +```js live +console.log(x); // undefined. (Hoisted but uninitialized, risk of unexpected behavior) +console.log(y); // ReferenceError: Cannot access 'y' before initialization. (Not hoisted) +console.log(z); // ReferenceError: Cannot access 'z' before initialization. (Not hoisted) + // Avoid using var var x = 10; // Hoisted to the top of the function or global scope @@ -43,7 +48,7 @@ const z = 30; // Block-scoped, not hoisted to the top To avoid confusion and potential errors, always declare your variables at the top of their scope. This makes it clear where the variables are coming from and ensures they are initialized before use. -```js +```js live function example() { let a = 1; const b = 2; @@ -51,13 +56,14 @@ function example() { // Now use a and b console.log(a + b); } +example(); ``` ### Declare functions before calling them Function declarations are hoisted, but function expressions are not. To avoid issues, always declare functions before calling them. -```js +```js live // Function declaration (hoisted) function myFunction() { console.log('Hello, world!'); @@ -75,10 +81,10 @@ anotherFunction(); // No issues here Using undeclared variables can lead to unexpected behavior due to hoisting. Always declare your variables before using them. -```js +```js live // Avoid this function badExample() { - x = 10; // x is not declared + x = 10; // ReferenceError in strict mode console.log(x); } @@ -87,6 +93,9 @@ function goodExample() { let x = 10; // x is declared console.log(x); } + +goodExample(); +badExample(); ``` ## Further reading From c976667302398f590b9640f42de49865bd2e6095 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:05:45 +0500 Subject: [PATCH 11/56] exec: what-is-the-difference-between-double-equal-and-triple-equal --- .../en-US.mdx | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx b/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx index f824108..098fc79 100644 --- a/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx +++ b/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx @@ -18,28 +18,28 @@ title: What is the difference between `==` and `===` in JavaScript? The `==` operator checks for equality between two values but performs type coercion if the values are of different types. This means that JavaScript will attempt to convert the values to a common type before making the comparison. -```js -42 == '42'; // true -0 == false; // true -null == undefined; // true -[] == false; // true -'' == false; // true +```js live +console.log(42 == '42'); // true +console.log(0 == false); // true +console.log(null == undefined); // true +console.log([] == false); // true +console.log('' == false); // true ``` In these examples, JavaScript converts the operands to the same type before making the comparison. For example, `42 == '42'` is true because the string `'42'` is converted to the number `42` before comparison. However, when using `==`, unintuitive results can happen: -```js -1 == [1]; // true -0 == ''; // true -0 == '0'; // true -'' == '0'; // false +```js live +console.log(1 == [1]); // true +console.log(0 == ''); // true +console.log(0 == '0'); // true +console.log('' == '0'); // false ``` As a general rule of thumb, never use the `==` operator, except for convenience when comparing against `null` or `undefined`, where `a == null` will return `true` if `a` is `null` or `undefined`. -```js +```js live var a = null; console.log(a == null); // true console.log(a == undefined); // true @@ -49,7 +49,7 @@ console.log(a == undefined); // true The `===` operator, also known as the strict equality operator, checks for equality between two values without performing type coercion. This means that both the value and the type must be the same for the comparison to return true. -```js +```js live console.log(42 === '42'); // false console.log(0 === false); // false console.log(null === undefined); // false @@ -59,7 +59,7 @@ console.log('' === false); // false For these comparisons, no type conversion is performed, so the statement returns `false` if the types are different. For instance, `42 === '42'` is `false` because the types (number and string) are different. -```js +```js live // Comparison with type coercion (==) console.log(42 == '42'); // true console.log(0 == false); // true From f9b6c18b41e5015655472583c2d66c8294e4d9c3 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:20:52 +0500 Subject: [PATCH 12/56] exec: what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items --- .../en-US.mdx | 54 +++++++++++++------ 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx b/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx index 2b2f372..e6a7f0d 100644 --- a/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx +++ b/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx @@ -10,7 +10,7 @@ There are multiple ways to iterate over object properties as well as arrays in J The `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties -```js +```js live const obj = { a: 1, b: 2, @@ -29,7 +29,7 @@ for (const key in obj) { `Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array. -```js +```js live const obj = { a: 1, b: 2, @@ -45,7 +45,7 @@ Most common ways to iterate over array are using `for` loop and `Array.prototype **Using `for` loop** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; for (let index = 0; index < array.length; index++) { console.log(array[index]); @@ -54,7 +54,7 @@ for (let index = 0; index < array.length; index++) { **Using `Array.prototype.forEach` method** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; array.forEach((number, index) => { console.log(`${number} at index ${index}`); @@ -65,7 +65,7 @@ array.forEach((number, index) => { This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index. -```js +```js live const numbers = [1, 2, 3, 4, 5]; for (const number of numbers) { @@ -89,7 +89,12 @@ Iterating over object properties and array is very common in JavaScript and we h This loop iterates over all **enumerable** properties of an object, including those inherited from its prototype chain. -```js +```js live +const obj = { + status: 'working', + hoursWorked: 3, +}; + for (const property in obj) { console.log(property); } @@ -97,7 +102,12 @@ for (const property in obj) { Since `for...in` statement iterates over all the object's **enumerable** properties (including inherited enumerable properties). Hence most of the time you should check whether the property exists on directly on the object via `Object.hasOwn(object, property)` before using it. -```js +```js live +const obj = { + status: 'working', + hoursWorked: 3, +}; + for (const property in obj) { if (Object.hasOwn(obj, property)) { console.log(property); @@ -111,7 +121,12 @@ Note that `obj.hasOwnProperty()` is not recommended because it doesn't work for `Object.keys()` is a static method that will return an array of all the enumerable property names of the object that you pass it. Since `Object.keys()` returns an array, you can also use the array iteration approaches listed below to iterate through it. -```js +```js live +const obj = { + status: 'working', + hoursWorked: 3, +}; + Object.keys(obj).forEach((property) => { console.log(property); }); @@ -121,7 +136,7 @@ Object.keys(obj).forEach((property) => { This method returns an array of an object's enumerable properties in `[key, value]` pairs. -```js +```js live const obj = { a: 1, b: 2, c: 3 }; Object.entries(obj).forEach(([key, value]) => { console.log(`${key}: ${value}`); @@ -130,7 +145,8 @@ Object.entries(obj).forEach(([key, value]) => { ### `Object.getOwnPropertyNames()` -```js +```js live +const obj = { a: 1, b: 2, c: 3 }; Object.getOwnPropertyNames(obj).forEach((property) => { console.log(property); }); @@ -142,7 +158,8 @@ Object.getOwnPropertyNames(obj).forEach((property) => { ### `for` loop -```js +```js live +const arr = [1, 2, 3, 4, 5]; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } @@ -150,7 +167,8 @@ for (var i = 0; i < arr.length; i++) { A common pitfall here is that `var` is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces `let` which has block scope and it is recommended to use `let` over `var`. -```js +```js live +const arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } @@ -158,9 +176,10 @@ for (let i = 0; i < arr.length; i++) { ### `Array.prototype.forEach()` -```js +```js live +const arr = [1, 2, 3, 4, 5]; arr.forEach((element, index) => { - console.log(element, index); + console.log(`${element} at index ${index}`); }); ``` @@ -168,7 +187,8 @@ The `Array.prototype.forEach()` method can be more convenient at times if you do ### `for...of` statement -```js +```js live +const arr = [1, 2, 3, 4, 5]; for (let element of arr) { console.log(element); } @@ -180,11 +200,11 @@ Most of the time, prefer the `.forEach` method, but it really depends on what yo Also, when using the `for...of` statement, if you need to access both the index and value of each array element, you can do so with ES2015 `Array.prototype.entries()` method: -```js +```js live const arr = ['a', 'b', 'c']; for (let [index, elem] of arr.entries()) { - console.log(index, ': ', elem); + console.log(index, elem); } ``` From 1a59dbdcfe57c0196ece97fde233ebaebd05ffa2 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:27:19 +0500 Subject: [PATCH 13/56] exec: what-is-the-purpose-of-the-break-and-continue-statements --- .../en-US.mdx | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx b/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx index b3aff52..f01ee3d 100644 --- a/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx +++ b/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx @@ -6,7 +6,7 @@ title: What is the purpose of the `break` and `continue` statements? The `break` statement is used to exit a loop or switch statement prematurely, while the `continue` statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a `for` loop, `break` will stop the loop entirely, and `continue` will skip to the next iteration. -```js +```js live for (let i = 0; i < 10; i++) { if (i === 5) break; // exits the loop when i is 5 console.log(i); @@ -28,7 +28,7 @@ The `break` statement is used to exit a loop or a switch statement before it has #### Example in a loop -```js +```js live for (let i = 0; i < 10; i++) { if (i === 5) break; // exits the loop when i is 5 console.log(i); @@ -38,18 +38,22 @@ for (let i = 0; i < 10; i++) { #### Example in a switch statement -```js -switch (day) { - case 1: - console.log('Monday'); - break; - case 2: - console.log('Tuesday'); - break; - // other cases - default: - console.log('Invalid day'); +```js live +function printDayOfWeek(day) { + switch (day) { + case 1: + console.log('Monday'); + break; + case 2: + console.log('Tuesday'); + break; + // other cases + default: + console.log('Invalid day'); + } } +printDayOfWeek(2); // Tuesday +printDayOfWeek('myDay'); // Invalid day ``` ### `continue` statement @@ -58,7 +62,7 @@ The `continue` statement is used to skip the current iteration of a loop and pro #### Example in a loop -```js +```js live for (let i = 0; i < 10; i++) { if (i === 5) continue; // skips the iteration when i is 5 console.log(i); From 93fc6c7dfe2e4e176bf100cd82848230606558a2 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:29:59 +0500 Subject: [PATCH 14/56] exec: what-is-the-ternary-operator-and-how-is-it-used --- .../what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx b/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx index d67e1ac..62e8f9a 100644 --- a/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx +++ b/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx @@ -30,7 +30,7 @@ condition ? expr1 : expr2; Here is a basic example of the ternary operator: -```js +```js live let age = 18; let canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote); // Output: Yes @@ -42,7 +42,7 @@ In this example, the condition `age >= 18` is evaluated. If it is `true`, the st You can also nest ternary operators, although it can make the code harder to read: -```js +```js live let score = 85; let grade = score >= 90 From 52b9eb3815c2fbb1a4dddf0aac52b9edb5c89b64 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:31:40 +0500 Subject: [PATCH 15/56] exec: how-do-you-access-the-index-of-an-element-in-an-array-during-iteration --- .../en-US.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx b/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx index 646f4e7..293b1e8 100644 --- a/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx +++ b/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx @@ -6,7 +6,7 @@ title: How do you access the index of an element in an array during iteration? To access the index of an element in an array during iteration, you can use methods like `forEach`, `map`, `for...of` with `entries`, or a traditional `for` loop. For example, using `forEach`: -```js +```js live const array = ['a', 'b', 'c']; array.forEach((element, index) => { console.log(index, element); @@ -19,7 +19,7 @@ array.forEach((element, index) => { The `forEach` method executes a provided function once for each array element. The callback function takes three arguments: the current element, the index of the current element, and the array itself. -```js +```js live const array = ['a', 'b', 'c']; array.forEach((element, index) => { console.log(index, element); @@ -30,7 +30,7 @@ array.forEach((element, index) => { The `map` method creates a new array populated with the results of calling a provided function on every element in the calling array. The callback function also takes three arguments: the current element, the index of the current element, and the array itself. -```js +```js live const array = ['a', 'b', 'c']; array.map((element, index) => { console.log(index, element); @@ -41,7 +41,7 @@ array.map((element, index) => { The `for...of` loop can be combined with the `entries` method to access both the index and the element. -```js +```js live const array = ['a', 'b', 'c']; for (const [index, element] of array.entries()) { console.log(index, element); @@ -52,7 +52,7 @@ for (const [index, element] of array.entries()) { A traditional `for` loop gives you direct access to the index. -```js +```js live const array = ['a', 'b', 'c']; for (let index = 0; index < array.length; index++) { console.log(index, array[index]); From 3e044c80661b143e218785ea6ed26ce9a564c257 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:33:57 +0500 Subject: [PATCH 16/56] exec: what-is-the-purpose-of-the-switch-statement --- .../what-is-the-purpose-of-the-switch-statement/en-US.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx b/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx index 7903802..0f65637 100644 --- a/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx +++ b/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx @@ -57,7 +57,7 @@ switch (expression) { Here is an example of a `switch` statement in action: -```js +```js live let fruit = 'apple'; switch (fruit) { @@ -81,7 +81,7 @@ In this example, the output will be `Apple is red.` because the value of `fruit` If the `break` statement is omitted, the `switch` statement will continue to execute the subsequent `case` blocks until it encounters a `break` or the end of the `switch` block. This is known as fall-through behavior. -```js +```js live let day = 2; switch (day) { From 5917f8d523f37403de71216a1fba127f92123b2d Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:41:16 +0500 Subject: [PATCH 17/56] exec: what-are-rest-parameters-and-how-are-they-used --- .../en-US.mdx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx b/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx index a30038d..53c7832 100644 --- a/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx +++ b/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx @@ -6,7 +6,7 @@ title: What are rest parameters and how are they used? Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (`...`) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance. -```js +```js live function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } @@ -26,10 +26,12 @@ Rest parameters allow a function to accept an indefinite number of arguments as The syntax for rest parameters is straightforward. You place three dots before the last parameter in the function definition: -```js +```js live function myFunction(a, b, ...rest) { // 'rest' is an array containing the remaining arguments + console.log(rest); // [3, 4, 5] } +myFunction(1, 2, 3, 4, 5); ``` ### Usage @@ -40,7 +42,7 @@ Rest parameters are useful in various scenarios, such as when you need to handle Here's a simple example of a function that sums an indefinite number of arguments: -```js +```js live function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } @@ -54,7 +56,7 @@ In this example, the `sum` function uses the rest parameter `numbers` to collect Rest parameters can also be used to combine multiple arrays into one: -```js +```js live function combineArrays(...arrays) { return arrays.flat(); } From b3b8e22d767919c315d3ec445af98b81d748c493 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sun, 2 Mar 2025 20:44:46 +0500 Subject: [PATCH 18/56] exec: explain-the-concept-of-the-spread-operator-and-its-uses --- .../en-US.mdx | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx b/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx index 1a8864f..a5dd4cf 100644 --- a/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx +++ b/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx @@ -6,22 +6,26 @@ title: Explain the concept of the spread operator and its uses The spread operator (`...`) in JavaScript allows you to expand elements of an iterable (like an array or object) into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function. -```js +```js live // Copying an array const arr1 = [1, 2, 3]; const arr2 = [...arr1]; +console.log(arr2); // Output: [1, 2, 3] // Merging arrays const arr3 = [4, 5, 6]; const mergedArray = [...arr1, ...arr3]; +console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6] // Copying an object const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1 }; +console.log(obj2); // Output: { a: 1, b: 2 } // Merging objects const obj3 = { c: 3, d: 4 }; const mergedObject = { ...obj1, ...obj3 }; +console.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 } // Passing array elements as function arguments const sum = (x, y, z) => x + y + z; @@ -37,7 +41,7 @@ console.log(sum(...numbers)); // Output: 6 The spread operator can be used to create a shallow copy of an array. This is useful when you want to duplicate an array without affecting the original array. -```js +```js live const arr1 = [1, 2, 3]; const arr2 = [...arr1]; console.log(arr2); // Output: [1, 2, 3] @@ -47,7 +51,7 @@ console.log(arr2); // Output: [1, 2, 3] You can use the spread operator to merge multiple arrays into one. This is a concise and readable way to combine arrays. -```js +```js live const arr1 = [1, 2, 3]; const arr3 = [4, 5, 6]; const mergedArray = [...arr1, ...arr3]; @@ -58,7 +62,7 @@ console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6] Similar to arrays, the spread operator can be used to create a shallow copy of an object. This is useful for duplicating objects without affecting the original object. -```js +```js live const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1 }; console.log(obj2); // Output: { a: 1, b: 2 } @@ -68,7 +72,7 @@ console.log(obj2); // Output: { a: 1, b: 2 } The spread operator can also be used to merge multiple objects into one. This is particularly useful for combining properties from different objects. -```js +```js live const obj1 = { a: 1, b: 2 }; const obj3 = { c: 3, d: 4 }; const mergedObject = { ...obj1, ...obj3 }; @@ -79,7 +83,7 @@ console.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 } The spread operator allows you to pass elements of an array as individual arguments to a function. This is useful for functions that accept multiple arguments. -```js +```js live const sum = (x, y, z) => x + y + z; const numbers = [1, 2, 3]; console.log(sum(...numbers)); // Output: 6 From f0f1c016afac2ef4ff1f95d52be341337eca51b0 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 2 Mar 2025 16:41:33 +0000 Subject: [PATCH 19/56] [auto] regenerate table of contents --- README.md | 53 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index d27c4e4..9647747 100644 --- a/README.md +++ b/README.md @@ -1494,7 +1494,7 @@ There are multiple ways to iterate over object properties as well as arrays in J The `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties -```js +```js live const obj = { a: 1, b: 2, @@ -1513,7 +1513,7 @@ for (const key in obj) { `Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array. -```js +```js live const obj = { a: 1, b: 2, @@ -1529,7 +1529,7 @@ Most common ways to iterate over array are using `for` loop and `Array.prototype **Using `for` loop** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; for (let index = 0; index < array.length; index++) { console.log(array[index]); @@ -1538,7 +1538,7 @@ for (let index = 0; index < array.length; index++) { **Using `Array.prototype.forEach` method** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; array.forEach((number, index) => { console.log(`${number} at index ${index}`); @@ -1549,7 +1549,7 @@ array.forEach((number, index) => { This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index. -```js +```js live const numbers = [1, 2, 3, 4, 5]; for (const number of numbers) { @@ -2322,9 +2322,9 @@ Template literals are a feature in JavaScript that allow for easier string inter Example: -```js -const name = 'John'; -const greeting = `Hello, ${name}!`; +```js live +const myName = 'John'; +const greeting = `Hello, ${myName}!`; console.log(greeting); // Output: Hello, John! ``` @@ -2365,14 +2365,16 @@ console.log(result); // "Hello world! How are you?" The spread operator, represented by three dots (`...`), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function. -```js +```js live const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; -const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6] +const combined = [...arr1, ...arr2]; +console.log(combined); // [1, 2, 3, 4, 5, 6] const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; -const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 } +const combinedObj = { ...obj1, ...obj2 }; +console.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 } ``` @@ -2565,16 +2567,17 @@ let b = 10; To avoid problems related to hoisting, always declare variables at the top of their scope using `let` or `const` instead of `var`. This ensures that variables are block-scoped and not hoisted to the top of their containing function or global scope. Additionally, declare functions before they are called to avoid issues with function hoisting. -```js +```js live // Use let or const let x = 10; const y = 20; +console.log(x, y); // Output: 10 20 // Declare functions before calling them function myFunction() { console.log('Hello, world!'); } -myFunction(); +myFunction(); // Output: 'Hello, world!' ``` @@ -2615,7 +2618,7 @@ There are multiple ways to iterate over object properties as well as arrays in J The `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties -```js +```js live const obj = { a: 1, b: 2, @@ -2634,7 +2637,7 @@ for (const key in obj) { `Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array. -```js +```js live const obj = { a: 1, b: 2, @@ -2650,7 +2653,7 @@ Most common ways to iterate over array are using `for` loop and `Array.prototype **Using `for` loop** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; for (let index = 0; index < array.length; index++) { console.log(array[index]); @@ -2659,7 +2662,7 @@ for (let index = 0; index < array.length; index++) { **Using `Array.prototype.forEach` method** -```js +```js live let array = [1, 2, 3, 4, 5, 6]; array.forEach((number, index) => { console.log(`${number} at index ${index}`); @@ -2670,7 +2673,7 @@ array.forEach((number, index) => { This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index. -```js +```js live const numbers = [1, 2, 3, 4, 5]; for (const number of numbers) { @@ -2698,7 +2701,7 @@ There are also other inbuilt methods available which are suitable for specific s The `break` statement is used to exit a loop or switch statement prematurely, while the `continue` statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a `for` loop, `break` will stop the loop entirely, and `continue` will skip to the next iteration. -```js +```js live for (let i = 0; i < 10; i++) { if (i === 5) break; // exits the loop when i is 5 console.log(i); @@ -2738,7 +2741,7 @@ The ternary operator is a shorthand for an `if-else` statement in JavaScript. It To access the index of an element in an array during iteration, you can use methods like `forEach`, `map`, `for...of` with `entries`, or a traditional `for` loop. For example, using `forEach`: -```js +```js live const array = ['a', 'b', 'c']; array.forEach((element, index) => { console.log(index, element); @@ -2786,7 +2789,7 @@ switch (expression) { Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (`...`) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance. -```js +```js live function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } @@ -2808,22 +2811,26 @@ console.log(sum(1, 2, 3, 4)); // Output: 10 The spread operator (`...`) in JavaScript allows you to expand elements of an iterable (like an array or object) into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function. -```js +```js live // Copying an array const arr1 = [1, 2, 3]; const arr2 = [...arr1]; +console.log(arr2); // Output: [1, 2, 3] // Merging arrays const arr3 = [4, 5, 6]; const mergedArray = [...arr1, ...arr3]; +console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6] // Copying an object const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1 }; +console.log(obj2); // Output: { a: 1, b: 2 } // Merging objects const obj3 = { c: 3, d: 4 }; const mergedObject = { ...obj1, ...obj3 }; +console.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 } // Passing array elements as function arguments const sum = (x, y, z) => x + y + z; @@ -3005,7 +3012,7 @@ A parameter is a variable in the declaration of a function, while an argument is Hoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way. -```js +```js live // Function declaration hoistedFunction(); // Works fine function hoistedFunction() { From be56334aa3eb779fc47c553dce75fab06a02f774 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Thu, 6 Mar 2025 23:53:40 +0500 Subject: [PATCH 20/56] exec: what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax --- .../en-US.mdx | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx b/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx index 86c4993..bc1a36a 100644 --- a/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx +++ b/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx @@ -15,7 +15,7 @@ title: What are the benefits of using spread syntax in JavaScript and how is it **Rest syntax** is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments. -```js +```js live // Using rest syntax in a function function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); @@ -34,14 +34,14 @@ ES2015's spread syntax is very useful when coding in a functional paradigm as we The spread syntax provides a concise way to create copies of arrays or objects without modifying the originals. This is useful for creating immutable data structures. However do note that arrays copied via the spread operator are shallowly-copied. -```js +```js live // Copying arrays const array = [1, 2, 3]; const newArray = [...array]; console.log(newArray); // Output: [1, 2, 3] // Copying objects -const obj = { name: 'John', age: 30 }; +const person = { name: 'John', age: 30 }; const newObj = { ...person, city: 'New York' }; console.log(newObj); // Output: { name: 'John', age: 30, city: 'New York' } ``` @@ -50,7 +50,7 @@ console.log(newObj); // Output: { name: 'John', age: 30, city: 'New York' } The spread syntax allows you to merge arrays or objects by spreading their elements/properties into a new array or object. -```js +```js live // Merging arrays const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; @@ -67,16 +67,17 @@ const obj2 = { }; const merged = { ...obj1, ...obj2 }; -console.log(copyOfTodd); // Output: { foo: "bar", qux: "baz" } +console.log(merged); // Output: { foo: "bar", qux: "baz" } ``` ### Passing arguments to functions Use the spread syntax to pass an array of values as individual arguments to a function, avoiding the need for `apply()`. -```js +```js live const numbers = [1, 2, 3]; -Math.max(...numbers); // Same as Math.max(1, 2, 3) +const max = Math.max(...numbers); // Same as Math.max(1, 2, 3) +console.log(max); // Output: 3 ``` ### Array vs object spreads @@ -85,7 +86,7 @@ Only iterable values like `Array`s and `String`s can be spread in an array. Tryi Spreading object into array: -```js +```js live const person = { name: 'Todd', age: 29, @@ -95,9 +96,10 @@ const array = [...person]; // Error: Uncaught TypeError: person is not iterable On the other hand, arrays can be spread into objects. -```js +```js live const array = [1, 2, 3]; -const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 } +const obj = { ...array }; +console.log(obj); // { 0: 1, 1: 2, 2: 3 } ``` ## Rest syntax @@ -108,7 +110,7 @@ The rest syntax (`...`) in JavaScript allows you to represent an indefinite numb The rest syntax can be used in function parameters to collect all remaining arguments into an array. This is particularly useful when you don't know how many arguments will be passed to the function. -```js +```js live function addFiveToABunchOfNumbers(...numbers) { return numbers.map((x) => x + 5); } @@ -119,7 +121,7 @@ console.log(result); // Output: [9, 10, 11, 12, 13, 14, 15] Provides a cleaner syntax than using the `arguments` object, which is unsupported for arrow functions and represents **all** arguments whereas the usage of the rest syntax below allows `remaining` to represent the 3rd argument and beyond. -```js +```js live const [first, second, ...remaining] = [1, 2, 3, 4, 5]; console.log(first); // Output: 1 console.log(second); // Output: 2 @@ -128,9 +130,9 @@ console.log(remaining); // Output: [3, 4, 5] Note that the rest parameters must be at the end. The rest parameters gather all remaining arguments, so the following does not make sense and causes an error: -```js +```js live function addFiveToABunchOfNumbers(arg1, ...numbers, arg2) { - // Error: Uncaught Rest element must be last element. + // Error: Rest parameter must be last formal parameter. } ``` @@ -138,21 +140,27 @@ function addFiveToABunchOfNumbers(arg1, ...numbers, arg2) { The rest syntax can be used in array destructuring to collect the remaining elements into a new array. -```js -const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4] +```js live +const [a, b, ...rest] = [1, 2, 3, 4]; +console.log(a); // Output: 1 +console.log(b); // Output: 2 +console.log(rest); // Output: [3, 4] ``` ### Object destructuring The rest syntax can be used in object destructuring to collect the remaining properties into a new object. -```js +```js live const { e, f, ...others } = { e: 1, f: 2, g: 3, h: 4, -}; // e: 1, f: 2, others: { g: 3, h: 4 } +}; +console.log(e); // Output: 1 +console.log(f); // Output: 2 +console.log(others); // Output: { g: 3, h: 4 } ``` ## Further Reading From f61faa7a1729cd7d7c38d3f6f5fd9002b4220544 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 00:07:21 +0500 Subject: [PATCH 21/56] exec: explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function --- .../en-US.mdx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx b/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx index f00aa62..233b88e 100644 --- a/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx +++ b/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx @@ -10,7 +10,7 @@ If you try to invoke a function expression before it is declared, you will get a Function declarations can be called in the enclosing scope even before they are declared. -```js +```js live foo(); // 'FOOOOO' function foo() { console.log('FOOOOO'); @@ -19,7 +19,7 @@ function foo() { Function expressions if called before they are declared will result in an error. -```js +```js live foo(); // Uncaught TypeError: foo is not a function var foo = function () { console.log('FOOOOO'); @@ -28,11 +28,13 @@ var foo = function () { Another key difference is in the scope of the function name. Function expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or `undefined`. -```js +```js live const myFunc = function namedFunc() { console.log(namedFunc); // Works }; -console.log(namedFunc); // undefined + +myFunc(); // Runs the function and logs the function reference +console.log(namedFunc); // ReferenceError: namedFunc is not defined ``` **Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords. @@ -43,20 +45,22 @@ console.log(namedFunc); // undefined A function declaration is a statement that defines a function with a name. It is typically used to declare a function that can be called multiple times throughout the enclosing scope. -```js +```js live function foo() { console.log('FOOOOO'); } +foo(); // 'FOOOOO' ``` ## Function expressions A function expression is an expression that defines a function and assigns it to a variable. It is often used when a function is needed only once or in a specific context. -```js +```js live var foo = function () { console.log('FOOOOO'); }; +foo(); // 'FOOOOO' ``` **Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords. @@ -69,7 +73,7 @@ The key difference is that function declarations have its body hoisted but the b Function declarations: -```js +```js live foo(); // 'FOOOOO' function foo() { console.log('FOOOOO'); @@ -78,7 +82,7 @@ function foo() { Function expressions: -```js +```js live foo(); // Uncaught TypeError: foo is not a function var foo = function () { console.log('FOOOOO'); @@ -89,11 +93,13 @@ var foo = function () { Function expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in `undefined` and calling it will result in an error. -```js +```js live const myFunc = function namedFunc() { console.log(namedFunc); // Works }; -console.log(namedFunc); // undefined + +myFunc(); // Runs the function and logs the function reference +console.log(namedFunc); // ReferenceError: namedFunc is not defined ``` ## When to use each From 730aee998269ea1954f4b4f5e06015e7acbe4a69 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 00:10:17 +0500 Subject: [PATCH 22/56] exec: what-is-the-difference-between-a-parameter-and-an-argument --- .../en-US.mdx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx b/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx index 53e183d..450b1f7 100644 --- a/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx +++ b/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx @@ -30,8 +30,11 @@ Arguments are the actual values that are passed to the function when it is invok Example: -```js -greet('Alice'); +```js live +function greet(name) { + console.log('Hello, ' + name); +} +greet('Alice'); // Output: "Hello, Alice" ``` In this example, `"Alice"` is an argument. @@ -43,14 +46,14 @@ In this example, `"Alice"` is an argument. ### Example combining both -```js +```js live function add(a, b) { // a and b are parameters return a + b; } const result = add(2, 3); // 2 and 3 are arguments -console.log(result); // Outputs: 5 +console.log(result); // Output: 5 ``` ## Further reading From 7cf0b24a276d1d4f864779080e8e7e14252c237f Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 00:17:50 +0500 Subject: [PATCH 23/56] exec: whats-the-difference-between-call-and-apply --- .../en-US.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/questions/whats-the-difference-between-call-and-apply/en-US.mdx b/questions/whats-the-difference-between-call-and-apply/en-US.mdx index a61016e..8b08c46 100644 --- a/questions/whats-the-difference-between-call-and-apply/en-US.mdx +++ b/questions/whats-the-difference-between-call-and-apply/en-US.mdx @@ -11,7 +11,7 @@ title: What's the difference between `.call` and `.apply` in JavaScript? Assuming we have a function `add`, the function can be invoked using `.call` and `.apply` in the following manner: -```js +```js live function add(a, b) { return a + b; } @@ -28,7 +28,7 @@ Both `.call` and `.apply` are used to invoke functions and the first parameter w An easy way to remember this is C for `call` and comma-separated and A for `apply` and an array of arguments. -```js +```js live function add(a, b) { return a + b; } @@ -39,7 +39,7 @@ console.log(add.apply(null, [1, 2])); // 3 With ES6 syntax, we can invoke `call` using an array along with the spread operator for the arguments. -```js +```js live function add(a, b) { return a + b; } @@ -53,7 +53,7 @@ console.log(add.call(null, ...[1, 2])); // 3 `.call` and `.apply` can set the `this` context explicitly when invoking methods on different objects. -```js +```js live const person = { name: 'John', greet() { @@ -71,7 +71,7 @@ person.greet.apply(anotherPerson); // Hello, my name is Alice Both `.call` and `.apply` allow borrowing methods from one object and using them in the context of another. This is useful when passing functions as arguments (callbacks) and the original `this` context is lost. `.call` and `.apply` allow the function to be invoked with the intended `this` value. -```js +```js live function greet() { console.log(`Hello, my name is ${this.name}`); } @@ -87,7 +87,7 @@ greet.call(person2); // Hello, my name is Alice `.apply` can be used with object methods by passing the object as the first argument followed by the usual parameters. -```js +```js live const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; From 40c09e476f712939e8e2c2e6196a786e34434d8e Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 00:44:56 +0500 Subject: [PATCH 24/56] partial fix: can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions --- .../en-US.mdx | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/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 b/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 index 7b31d24..2fca734 100644 --- a/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 +++ b/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 @@ -7,7 +7,7 @@ subtitle: How does this new syntax differ from other functions? Arrow functions provide a concise syntax for writing functions in JavaScript. They are particularly useful for maintaining the `this` context within methods and callbacks. For example, in an event handler or array method like `map`, arrow functions can simplify the code and avoid issues with `this` binding. -```javascript +```js live const numbers = [1, 2, 3]; const doubled = numbers.map((n) => n * 2); console.log(doubled); // [2, 4, 6] @@ -21,30 +21,35 @@ console.log(doubled); // [2, 4, 6] Arrow functions provide a more concise way to write functions. This is especially useful for short functions or callbacks. -```javascript +```js live // Traditional function const add = function (a, b) { return a + b; }; // Arrow function -const add = (a, b) => a + b; +const anotherAdd = (a, b) => a + b; + +console.log(add(2, 3)); // Output: 5 +console.log(anotherAdd(2, 3)); // Output: 5 ``` ### Lexical `this` binding Arrow functions do not have their own `this` context. Instead, they inherit `this` from the surrounding scope. This is particularly useful in methods and callbacks where the `this` context can be tricky. -```javascript +```js live function Timer() { this.seconds = 0; - setInterval(() => { - this.seconds++; + this.increment = () => { + this.seconds++; // 'this.seconds' is inherited from the outer scope console.log(this.seconds); - }, 1000); + }; } const timer = new Timer(); +timer.increment(); // 1 +timer.increment(); // 2 ``` In the example above, using a traditional function inside `setInterval` would require additional steps to maintain the correct `this` context. @@ -53,11 +58,11 @@ In the example above, using a traditional function inside `setInterval` would re Arrow functions are often used in array methods like `map`, `filter`, and `reduce` for cleaner and more readable code. -```javascript +```js live const numbers = [1, 2, 3, 4, 5]; // Traditional function -const doubled = numbers.map(function (n) { +const doubledTraditional = numbers.map(function (n) { return n * 2; }); @@ -71,7 +76,7 @@ console.log(doubled); // [2, 4, 6, 8, 10] Arrow functions can be used in event handlers to maintain the `this` context of the class or object. -```javascript +```js class Button { constructor() { this.count = 0; From 1b565537a325857a4253fde696dc88b6ecf38d14 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 00:53:33 +0500 Subject: [PATCH 25/56] exec: difference-between-function-person-var-person-person-and-var-person-new-person --- .../en-US.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx b/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx index 60fecd6..d1d6cba 100644 --- a/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx +++ b/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx @@ -33,12 +33,12 @@ This code defines a function named `Person` that takes a parameter `name` and as `const person = Person()` simply invoke the function's code. When you invoke `Person` as a regular function (i.e., without the `new` keyword), the function does not behave as a constructor. Instead, it executes its code and returns `undefined` if no return value is specified and that gets assigned to the variable intended as the instance. Invoking as such is a common mistake if the function is intended to be used as a constructor. -```js +```js live function Person(name) { this.name = name; } -const person = Person('John'); +const person = Person('John'); // Throws error in strict mode console.log(person); // undefined console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined ``` @@ -49,7 +49,7 @@ In this case, `Person('John')` does not create a new object. The `person` variab `const person = new Person()` creates an instance of the `Person` object using the new operator, which inherits from `Person.prototype`. An alternative would be to use `Object.create`, such as: `Object.create(Person.prototype)` and `Person.call(person, 'John')` initializes the object. -```js +```js live function Person(name) { this.name = name; } From 86aabc64952df993facb74d836526ad45680a55e Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:10:14 +0500 Subject: [PATCH 26/56] partial fix: what-is-the-definition-of-a-higher-order-function --- .../en-US.mdx | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx b/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx index b01b69d..c1ac02b 100644 --- a/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx +++ b/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx @@ -8,15 +8,11 @@ A higher-order function is any function that takes one or more functions as argu Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is `Array.prototype.map()`, which takes an array and a function as arguments. `Array.prototype.map()` then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are `Array.prototype.forEach()`, `Array.prototype.filter()`, and `Array.prototype.reduce()`. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. `Function.prototype.bind()` is an example that returns another function. -Imagine a scenario where we have an array of names that we need to transform to uppercase. +Imagine a scenario where we have an array of names that we need to transform to uppercase. The imperative way will be as such: -```js +```js live const names = ['irish', 'daisy', 'anna']; -``` - -The imperative way will be as such: -```js function transformNamesToUppercase(names) { const results = []; for (let i = 0; i < names.length; i++) { @@ -25,17 +21,19 @@ function transformNamesToUppercase(names) { return results; } -transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA'] +console.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA'] ``` Using `Array.prototype.map(transformerFn)` makes the code shorter and more declarative. -```js +```js live +const names = ['irish', 'daisy', 'anna']; + function transformNamesToUppercase(names) { return names.map((name) => name.toUpperCase()); } -transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA'] +console.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA'] ``` --- @@ -48,7 +46,7 @@ A higher-order function is a function that takes another function as an argument A higher-order function can take another function as an argument and execute it. -```js +```js live function greet(name) { return `Hello, ${name}!`; } @@ -66,7 +64,7 @@ In this example, the `greetName` function takes another function `greet` as an a A higher-order function can return another function. -```js +```js live function multiplier(factor) { return function (num) { return num * factor; @@ -86,7 +84,7 @@ In this example, the `multiplier` function returns a new function that multiplie 1. **Logging decorator**: A higher-order function that adds logging functionality to another function: -```js +```js live function withLogging(fn) { return function (...args) { console.log(`Calling ${fn.name} with arguments`, args); @@ -106,7 +104,7 @@ The `withLogging` function is a higher-order function that takes a function fn a 2. **Memoization**: A higher-order function that caches the results of a function to avoid redundant computations: -```js +```js live function memoize(fn) { const cache = new Map(); return function (...args) { From d837bb0b7ae409ebf78dfd90e371daaa5643ed13 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:15:13 +0500 Subject: [PATCH 27/56] exec: what-is-recursion-and-how-is-it-used-in-javascript --- .../en-US.mdx | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx b/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx index 40a55ae..ac8725f 100644 --- a/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx +++ b/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx @@ -6,13 +6,15 @@ title: What is recursion and how is it used in JavaScript? Recursion is a programming technique where a function calls itself to solve a problem. In JavaScript, recursion is used to solve problems that can be broken down into smaller, similar sub-problems. A base case is essential to stop the recursive calls and prevent infinite loops. For example, calculating the factorial of a number can be done using recursion: -```js +```js live function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); } + +console.log(factorial(4)); // Output: 24 ``` --- @@ -35,7 +37,7 @@ The factorial of a number `n` (denoted as `n!`) is the product of all positive i Here is how you can implement this in JavaScript: -```js +```js live function factorial(n) { if (n === 0) { // base case @@ -43,6 +45,8 @@ function factorial(n) { } return n * factorial(n - 1); // recursive case } + +console.log(factorial(4)); // Output: 24 ``` ### Example: Fibonacci sequence @@ -55,7 +59,7 @@ The Fibonacci sequence is another classic example of recursion. Each number in t Here is how you can implement this in JavaScript: -```js +```js live function fibonacci(n) { if (n === 0) { // base case @@ -67,19 +71,23 @@ function fibonacci(n) { } return fibonacci(n - 1) + fibonacci(n - 2); // recursive case } + +console.log(fibonacci(6)); // Output: 8 ``` ### Tail recursion Tail recursion is a special form of recursion where the recursive call is the last operation in the function. This can be optimized by some JavaScript engines to improve performance and prevent stack overflow. Here is an example of a tail-recursive factorial function: -```js +```js live function factorial(n, acc = 1) { if (n === 0) { return acc; } return factorial(n - 1, n * acc); } + +console.log(factorial(4)); // Output: 24 ``` ### Use cases for recursion From f8a5f10b57643919de89e49afc5d5936eae485b3 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:17:16 +0500 Subject: [PATCH 28/56] exec: what-are-default-parameters-and-how-are-they-used --- .../en-US.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx b/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx index f15728f..0b2712d 100644 --- a/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx +++ b/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx @@ -6,7 +6,7 @@ title: What are default parameters and how are they used? Default parameters in JavaScript allow you to set default values for function parameters if no value or `undefined` is passed. This helps avoid `undefined` values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition. -```js +```js live function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } @@ -35,7 +35,7 @@ function functionName(parameter1 = defaultValue1, parameter2 = defaultValue2) { Here is a simple example to illustrate how default parameters work: -```js +```js live function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } @@ -50,7 +50,7 @@ In this example, the `greet` function has a default parameter `name` with a defa You can also define multiple default parameters in a function: -```js +```js live function createUser(username = 'Anonymous', age = 18) { console.log(`Username: ${username}, Age: ${age}`); } @@ -66,7 +66,7 @@ In this example, the `createUser` function has two default parameters: `username You can also use expressions as default values for parameters: -```js +```js live function add(a = 0, b = a + 1) { return a + b; } From 75b98d6b8f4c4da44593bcd25228c90ccc915da2 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:35:57 +0500 Subject: [PATCH 29/56] exec: what-are-the-various-ways-to-create-objects-in-javascript --- .../en-US.mdx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx b/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx index fd192ad..26b182b 100644 --- a/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx +++ b/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx @@ -22,30 +22,34 @@ Creating objects in JavaScript involves several methods. Here are the various wa This is the simplest and most popular way to create objects in JavaScript. It involves defining a collection of key-value pairs within curly braces (`{}`). It can be used when you need to create a single object with a fixed set of properties. -```js +```js live const person = { firstName: 'John', lastName: 'Doe', age: 50, eyeColor: 'blue', }; + +console.log(person); // {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"} ``` ## `Object()` constructor This method involves using the `new` keyword with the built-in `Object` constructor to create an object. You can then add properties to the object using dot notation. It can be used when you need to create an object from a primitive value or to create an empty object. -```js +```js live const person = new Object(); person.firstName = 'John'; person.lastName = 'Doe'; + +console.log(person); // {firstName: "John", lastName: "Doe"} ``` ## `Object.create()` Method This method allows you to create a new object using an existing object as a prototype. The new object inherits properties and methods from the prototype object. It can be used when you need to create a new object with a specific prototype. -```js +```js live // Object.create() Method const personPrototype = { greet() { @@ -68,7 +72,7 @@ An object without a prototype can be created by doing `Object.create(null)`. Classes provide a more structured and familiar syntax (similar to other programming languages) for creating objects. They define a blueprint and use methods to interact with the object's properties. It can be used when you need to create complex objects with inheritance and encapsulation. -```js +```js live class Person { constructor(name, age) { this.name = name; @@ -94,7 +98,7 @@ Constructor functions are used to create reusable blueprints for objects. They d However, now that ES2015 classes are readily supported in modern browsers, there's little reason to use constructor functions to create objects. -```js +```js live // Constructor function function Person(name, age) { this.name = name; From 9d624e4b73e958965d6f03d640f39bbff73665b5 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:38:50 +0500 Subject: [PATCH 30/56] exec: explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties --- .../en-US.mdx | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx b/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx index ca58902..7851dd5 100644 --- a/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx +++ b/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the difference between dot notation and bracket notation for acce Dot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters. -```js +```js live const obj = { name: 'Alice', 'favorite color': 'blue' }; // Dot notation @@ -32,7 +32,7 @@ object.property; #### Example -```js +```js live const person = { name: 'Alice', age: 30, @@ -59,7 +59,7 @@ object['property']; #### Example -```js +```js live const person = { name: 'Alice', 'favorite color': 'blue', @@ -78,7 +78,12 @@ console.log(person[1]); // one #### Example with dynamic property names -```js +```js live +const person = { + name: 'Alice', + age: 30, +}; + const property = 'name'; console.log(person[property]); // Alice ``` From 08881bc0381a940dca97a386cf655db58f1c8467 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 01:40:37 +0500 Subject: [PATCH 31/56] exec: what-are-the-different-methods-for-iterating-over-an-array --- .../en-US.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx b/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx index 2ede973..92338b3 100644 --- a/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx +++ b/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx @@ -14,7 +14,7 @@ There are several methods to iterate over an array in JavaScript. The most commo The `for` loop is one of the most basic and versatile ways to iterate over an array. It allows you to control the iteration process completely. -```js +```js live const array = [1, 2, 3, 4, 5]; for (let i = 0; i < array.length; i++) { console.log(array[i]); @@ -25,7 +25,7 @@ for (let i = 0; i < array.length; i++) { The `for...of` loop is a more modern and readable way to iterate over arrays and other iterable objects. -```js +```js live const array = [1, 2, 3, 4, 5]; for (const element of array) { console.log(element); @@ -36,7 +36,7 @@ for (const element of array) { The `forEach` method executes a provided function once for each array element. -```js +```js live const array = [1, 2, 3, 4, 5]; array.forEach((element) => { console.log(element); @@ -47,7 +47,7 @@ array.forEach((element) => { The `map` method creates a new array populated with the results of calling a provided function on every element in the calling array. -```js +```js live const array = [1, 2, 3, 4, 5]; const newArray = array.map((element) => element * 2); console.log(newArray); // [2, 4, 6, 8, 10] @@ -57,7 +57,7 @@ console.log(newArray); // [2, 4, 6, 8, 10] The `filter` method creates a new array with all elements that pass the test implemented by the provided function. -```js +```js live const array = [1, 2, 3, 4, 5]; const filteredArray = array.filter((element) => element > 2); console.log(filteredArray); // [3, 4, 5] @@ -67,7 +67,7 @@ console.log(filteredArray); // [3, 4, 5] The `reduce` method executes a reducer function on each element of the array, resulting in a single output value. -```js +```js live const array = [1, 2, 3, 4, 5]; const sum = array.reduce( (accumulator, currentValue) => accumulator + currentValue, From a758de0d5dac5826337c7caa9402940fe922b16b Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:18:59 +0500 Subject: [PATCH 32/56] exec: how-do-you-add-remove-and-update-elements-in-an-array --- .../en-US.mdx | 42 ++++++++++++------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx b/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx index b5c1287..a9aa4cc 100644 --- a/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx +++ b/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx @@ -6,7 +6,7 @@ title: How do you add, remove, and update elements in an array? To add elements to an array, you can use methods like `push`, `unshift`, or `splice`. To remove elements, you can use `pop`, `shift`, or `splice`. To update elements, you can directly access the array index and assign a new value. -```js +```js live let arr = [1, 2, 3]; // Add elements @@ -21,8 +21,11 @@ arr.splice(1, 1); // [1, 2, 3] // Update elements arr[1] = 5; // [1, 5, 3] +console.log(arr); // Final state: [1, 5, 3] ``` +_Note:_ If you try to `console.log(arr)` after each operation in some environments (like Chrome DevTools), you may only see the final state of arr. This happens because the console sometimes keeps a live reference to the array instead of logging its state at the exact moment. To see intermediate states properly, store snapshots using console.log([...arr]) or print values immediately after each operation. + --- ## Adding elements to an array @@ -31,27 +34,30 @@ arr[1] = 5; // [1, 5, 3] The `push` method adds one or more elements to the end of an array and returns the new length of the array. -```js +```js live let arr = [1, 2, 3]; -arr.push(4); // arr is now [1, 2, 3, 4] +console.log(arr.push(4)); // Output: 4 (new length of array) +console.log(arr); // [1, 2, 3, 4] ``` ### Using `unshift` The `unshift` method adds one or more elements to the beginning of an array and returns the new length of the array. -```js +```js live let arr = [1, 2, 3]; -arr.unshift(0); // arr is now [0, 1, 2, 3] +console.log(arr.unshift(0)); // Output: 4 (new length of array) +console.log(arr); // [0, 1, 2, 3] ``` ### Using `splice` The `splice` method can add elements at any position in the array. The first parameter specifies the index at which to start changing the array, the second parameter specifies the number of elements to remove, and the rest are the elements to add. -```js +```js live let arr = [1, 2, 3]; -arr.splice(1, 0, 1.5); // arr is now [1, 1.5, 2, 3] +arr.splice(1, 0, 1.5); // Removes no element, but adds 1.5 +console.log(arr); // [1, 1.5, 2, 3] ``` ## Removing elements from an array @@ -60,27 +66,30 @@ arr.splice(1, 0, 1.5); // arr is now [1, 1.5, 2, 3] The `pop` method removes the last element from an array and returns that element. -```js +```js live let arr = [1, 2, 3]; -arr.pop(); // arr is now [1, 2] +console.log(arr.pop()); // Output: 3 +console.log(arr); // [1, 2] ``` ### Using `shift` The `shift` method removes the first element from an array and returns that element. -```js +```js live let arr = [1, 2, 3]; -arr.shift(); // arr is now [2, 3] +console.log(arr.shift()); // Output: 1 +console.log(arr); // [2, 3] ``` ### Using `splice` The `splice` method can also remove elements from any position in the array. The first parameter specifies the index at which to start changing the array, and the second parameter specifies the number of elements to remove. -```js -let arr = [1, 2, 3]; -arr.splice(1, 1); // arr is now [1, 3] +```js live +let arr = [1, 2, 3, 4]; +console.log(arr.splice(1, 2)); // Output: [2, 3] +console.log(arr); // [1, 4] ``` ## Updating elements in an array @@ -89,9 +98,10 @@ arr.splice(1, 1); // arr is now [1, 3] You can update elements in an array by directly accessing the index and assigning a new value. -```js +```js live let arr = [1, 2, 3]; -arr[1] = 5; // arr is now [1, 5, 3] +arr[1] = 5; +console.log(arr); // [1, 5, 3] ``` ## Further reading From c945e2b8a6ba4fcb890a8087f5cf0c21f2478904 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:28:29 +0500 Subject: [PATCH 33/56] partial fix: what-are-the-different-ways-to-copy-an-object-or-an-array --- .../en-US.mdx | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx b/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx index c106f4c..b55fa64 100644 --- a/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx +++ b/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx @@ -6,17 +6,20 @@ title: What are the different ways to copy an object or an array? To copy an object or an array in JavaScript, you can use several methods. For shallow copies, you can use the spread operator (`...`) or `Object.assign()`. For deep copies, you can use `JSON.parse(JSON.stringify())` or libraries like Lodash's `_.cloneDeep()`. -```js +```js live // Shallow copy of an array const originalArray = [1, 2, 3]; const shallowCopyArray = [...originalArray]; +console.log(shallowCopyArray); // [1, 2, 3] // Shallow copy of an object const originalObject = { a: 1, b: 2 }; const shallowCopyObject = { ...originalObject }; +console.log(shallowCopyObject); // { a: 1, b: 2 }; // Deep copy using JSON methods const deepCopyObject = JSON.parse(JSON.stringify(originalObject)); +console.log(deepCopyObject); // { a: 1, b: 2 }; ``` --- @@ -29,23 +32,26 @@ const deepCopyObject = JSON.parse(JSON.stringify(originalObject)); The spread operator (`...`) is a concise way to create a shallow copy of an array or an object. -```js +```js live // Shallow copy of an array const originalArray = [1, 2, 3]; const shallowCopyArray = [...originalArray]; +console.log(shallowCopyArray); // [1, 2, 3] // Shallow copy of an object const originalObject = { a: 1, b: 2 }; const shallowCopyObject = { ...originalObject }; +console.log(shallowCopyObject); // { a: 1, b: 2 }; ``` #### Using `Object.assign()` `Object.assign()` can also be used to create a shallow copy of an object. -```js +```js live const originalObject = { a: 1, b: 2 }; const shallowCopyObject = Object.assign({}, originalObject); +console.log(shallowCopyObject); // { a: 1, b: 2 }; ``` ### Deep copy @@ -54,9 +60,10 @@ const shallowCopyObject = Object.assign({}, originalObject); This method is a simple way to create a deep copy of an object or an array. However, it has limitations, such as not handling functions, `undefined`, or circular references. -```js +```js live const originalObject = { a: 1, b: { c: 2 } }; const deepCopyObject = JSON.parse(JSON.stringify(originalObject)); +console.log(deepCopyObject); // { a: 1, b: { c: 2 } } ``` #### Using Lodash's `_.cloneDeep()` @@ -66,7 +73,7 @@ Lodash is a popular utility library that provides a `_.cloneDeep()` method for d ```js const _ = require('lodash'); const originalObject = { a: 1, b: { c: 2 } }; -const deepCopyObject = _.cloneDeep(originalObject); +const deepCopyObject = _.cloneDeep(originalObject); // { a: 1, b: { c: 2 } } ``` ### Other methods @@ -75,7 +82,7 @@ const deepCopyObject = _.cloneDeep(originalObject); For custom deep copy logic, you can implement a recursive function. -```js +```js live function deepCopy(obj) { if (obj === null || typeof obj !== 'object') { return obj; @@ -96,6 +103,7 @@ function deepCopy(obj) { const originalObject = { a: 1, b: { c: 2 } }; const deepCopyObject = deepCopy(originalObject); +console.log(deepCopyObject); // { a: 1, b: { c: 2 } } ``` ## Further reading From a7b0bbc9d45da9944b42b9288d29c62bd136a03d Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:42:40 +0500 Subject: [PATCH 34/56] exec: explain-the-difference-between-shallow-copy-and-deep-copy --- .../en-US.mdx | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx b/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx index ebe47c8..aaed330 100644 --- a/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx +++ b/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx @@ -6,17 +6,20 @@ title: Explain the difference between shallow copy and deep copy A shallow copy duplicates the top-level properties of an object, but nested objects are still referenced. A deep copy duplicates all levels of an object, creating entirely new instances of nested objects. For example, using `Object.assign()` creates a shallow copy, while using libraries like `Lodash` or `structuredClone()` in modern JavaScript can create deep copies. -```js +```js live // Shallow copy example let obj1 = { a: 1, b: { c: 2 } }; let shallowCopy = Object.assign({}, obj1); shallowCopy.b.c = 3; -console.log(obj1.b.c); // Outputs: 3 +console.log(shallowCopy.b.c); // Output: 3 +console.log(obj1.b.c); // Output: 3 (original nested object changed too!) // Deep copy example -let deepCopy = JSON.parse(JSON.stringify(obj1)); +let obj2 = { a: 1, b: { c: 2 } }; +let deepCopy = JSON.parse(JSON.stringify(obj2)); deepCopy.b.c = 4; -console.log(obj1.b.c); // Outputs: 2 +console.log(deepCopy.b.c); // Output: 4 +console.log(obj2.b.c); // Output: 2 (original nested object remains unchanged) ``` --- @@ -29,11 +32,12 @@ A shallow copy creates a new object and copies the values of the original object #### Example -```js +```js live let obj1 = { a: 1, b: { c: 2 } }; let shallowCopy = Object.assign({}, obj1); shallowCopy.b.c = 3; -console.log(obj1.b.c); // Outputs: 3 +console.log(shallowCopy.b.c); // Output: 3 +console.log(obj1.b.c); // Output: 3 (original nested object changed too!) ``` In this example, `shallowCopy` is a shallow copy of `obj1`. Changing `shallowCopy.b.c` also changes `obj1.b.c` because `b` is a reference to the same object in both `obj1` and `shallowCopy`. @@ -44,11 +48,12 @@ A deep copy creates a new object and recursively copies all properties and neste #### Example -```js +```js live let obj1 = { a: 1, b: { c: 2 } }; let deepCopy = JSON.parse(JSON.stringify(obj1)); deepCopy.b.c = 4; -console.log(obj1.b.c); // Outputs: 2 +console.log(deepCopy.b.c); // Output: 4 +console.log(obj1.b.c); // Output: 2 (original nested object remains unchanged) ``` In this example, `deepCopy` is a deep copy of `obj1`. Changing `deepCopy.b.c` does not affect `obj1.b.c` because `b` is a completely new object in `deepCopy`. From 7e7cfb06ed0a60816b8f846c4ce788b12a19bba4 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:46:00 +0500 Subject: [PATCH 35/56] exec: what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects --- .../en-US.mdx | 38 +++++++++++-------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx b/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx index 15be82e..acdce67 100644 --- a/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx +++ b/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx @@ -6,14 +6,16 @@ title: What are the advantages of using the spread operator with arrays and obje The spread operator (`...`) in JavaScript allows you to easily copy arrays and objects, merge them, and add new elements or properties. It simplifies syntax and improves readability. For arrays, it can be used to concatenate or clone arrays. For objects, it can be used to merge objects or add new properties. -```js +```js live // Arrays const arr1 = [1, 2, 3]; -const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5] +const arr2 = [...arr1, 4, 5]; +console.log(arr2); // [1, 2, 3, 4, 5] // Objects const obj1 = { a: 1, b: 2 }; -const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 } +const obj2 = { ...obj1, c: 3 }; +console.log(obj2); // { a: 1, b: 2, c: 3 } ``` --- @@ -26,28 +28,31 @@ const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 } The spread operator allows you to create a shallow copy of an array easily. -```js +```js live const originalArray = [1, 2, 3]; -const clonedArray = [...originalArray]; // [1, 2, 3] +const clonedArray = [...originalArray]; +console.log(clonedArray); // [1, 2, 3] ``` #### Merging arrays You can concatenate multiple arrays into one. -```js +```js live const array1 = [1, 2]; const array2 = [3, 4]; -const mergedArray = [...array1, ...array2]; // [1, 2, 3, 4] +const mergedArray = [...array1, ...array2]; +console.log(mergedArray); // [1, 2, 3, 4] ``` #### Adding elements You can add new elements to an array without mutating the original array. -```js +```js live const array = [1, 2, 3]; -const newArray = [...array, 4, 5]; // [1, 2, 3, 4, 5] +const newArray = [...array, 4, 5]; +console.log(newArray); // [1, 2, 3, 4, 5] ``` ### Objects @@ -56,28 +61,31 @@ const newArray = [...array, 4, 5]; // [1, 2, 3, 4, 5] The spread operator allows you to create a shallow copy of an object. -```js +```js live const originalObject = { a: 1, b: 2 }; -const clonedObject = { ...originalObject }; // { a: 1, b: 2 } +const clonedObject = { ...originalObject }; +console.log(clonedObject); // { a: 1, b: 2 } ``` #### Merging objects You can merge multiple objects into one. -```js +```js live const object1 = { a: 1 }; const object2 = { b: 2 }; -const mergedObject = { ...object1, ...object2 }; // { a: 1, b: 2 } +const mergedObject = { ...object1, ...object2 }; +console.log(mergedObject); // { a: 1, b: 2 } ``` #### Adding properties You can add new properties to an object without mutating the original object. -```js +```js live const object = { a: 1, b: 2 }; -const newObject = { ...object, c: 3 }; // { a: 1, b: 2, c: 3 } +const newObject = { ...object, c: 3 }; +console.log(newObject); // { a: 1, b: 2, c: 3 } ``` ## Further reading From 5f539089660f64854286db54296fb43365ce9118 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:47:56 +0500 Subject: [PATCH 36/56] exec: how-do-you-check-if-an-object-has-a-specific-property --- .../en-US.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx b/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx index 7c9b9d8..28a75a4 100644 --- a/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx +++ b/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx @@ -6,7 +6,7 @@ title: How do you check if an object has a specific property? To check if an object has a specific property, you can use the `in` operator or the `hasOwnProperty` method. The `in` operator checks for both own and inherited properties, while `hasOwnProperty` checks only for own properties. -```js +```js live const obj = { key: 'value' }; // Using the `in` operator @@ -28,7 +28,7 @@ if (obj.hasOwnProperty('key')) { The `in` operator checks if a property exists in an object, including properties in the object's prototype chain. -```js +```js live const obj = { key: 'value' }; if ('key' in obj) { @@ -40,7 +40,7 @@ if ('key' in obj) { The `hasOwnProperty` method checks if a property exists directly on the object, not in its prototype chain. -```js +```js live const obj = { key: 'value' }; if (obj.hasOwnProperty('key')) { @@ -55,7 +55,7 @@ if (obj.hasOwnProperty('key')) { ### Example with inherited properties -```js +```js live const parentObj = { inheritedKey: 'inheritedValue' }; const childObj = Object.create(parentObj); childObj.ownKey = 'ownValue'; From 4b755303ca4dba25f62c1ff97cd6708468da60cf Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 02:49:56 +0500 Subject: [PATCH 37/56] exec: explain-the-concept-of-destructuring-assignment-for-objects-and-arrays --- .../en-US.mdx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx b/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx index e68ad8e..7161054 100644 --- a/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx +++ b/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the concept of destructuring assignment for objects and arrays Destructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces. For example: -```js +```js live // Array destructuring const [a, b] = [1, 2]; @@ -26,7 +26,7 @@ Array destructuring allows you to unpack values from arrays into distinct variab #### Basic example -```js +```js live const numbers = [1, 2, 3]; const [first, second, third] = numbers; @@ -39,7 +39,7 @@ console.log(third); // 3 You can skip values in the array by leaving an empty space between commas. -```js +```js live const numbers = [1, 2, 3]; const [first, , third] = numbers; @@ -51,7 +51,7 @@ console.log(third); // 3 You can assign default values in case the array does not have enough elements. -```js +```js live const numbers = [1]; const [first, second = 2] = numbers; @@ -65,7 +65,7 @@ Object destructuring allows you to unpack properties from objects into distinct #### Basic example -```js +```js live const person = { name: 'John', age: 30 }; const { name, age } = person; @@ -77,7 +77,7 @@ console.log(age); // 30 You can rename the variables while destructuring. -```js +```js live const person = { name: 'John', age: 30 }; const { name: personName, age: personAge } = person; @@ -89,7 +89,7 @@ console.log(personAge); // 30 You can assign default values in case the property does not exist in the object. -```js +```js live const person = { name: 'John' }; const { name, age = 25 } = person; @@ -101,7 +101,7 @@ console.log(age); // 25 You can destructure nested objects as well. -```js +```js live const person = { name: 'John', address: { city: 'New York', zip: '10001' } }; const { name, From 09838825cfe210cf59d760e976173496a453e11d Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 03:01:20 +0500 Subject: [PATCH 38/56] exec: how-do-you-reliably-determine-whether-an-object-is-empty --- .../en-US.mdx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx b/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx index eb22d8b..78473b2 100644 --- a/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx +++ b/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx @@ -6,7 +6,7 @@ title: How do you reliably determine whether an object is empty? To reliably determine whether an object is empty, you can use `Object.keys()` to check if the object has any enumerable properties. If the length of the array returned by `Object.keys()` is zero, the object is empty. -```js +```js live const isEmpty = (obj) => Object.keys(obj).length === 0; const obj = {}; @@ -21,7 +21,7 @@ console.log(isEmpty(obj)); // true The most common and reliable way to check if an object is empty is by using `Object.keys()`. This method returns an array of the object's own enumerable property names. If the length of this array is zero, the object is empty. -```js +```js live const isEmpty = (obj) => Object.keys(obj).length === 0; const obj1 = {}; @@ -35,7 +35,7 @@ console.log(isEmpty(obj2)); // false Another method is to use `Object.entries()`, which returns an array of the object's own enumerable property `[key, value]` pairs. If the length of this array is zero, the object is empty. -```js +```js live const isEmpty = (obj) => Object.entries(obj).length === 0; const obj1 = {}; @@ -49,7 +49,7 @@ console.log(isEmpty(obj2)); // false Similarly, you can use `Object.values()`, which returns an array of the object's own enumerable property values. If the length of this array is zero, the object is empty. -```js +```js live const isEmpty = (obj) => Object.values(obj).length === 0; const obj1 = {}; @@ -63,7 +63,7 @@ console.log(isEmpty(obj2)); // false You can also use a `for...in` loop to check if an object has any properties. If the loop doesn't iterate over any properties, the object is empty. -```js +```js live const isEmpty = (obj) => { for (let key in obj) { if (obj.hasOwnProperty(key)) { @@ -75,9 +75,12 @@ const isEmpty = (obj) => { const obj1 = {}; const obj2 = { key: 'value' }; +const childObj = Object.create(obj2); // Inherit from obj2 console.log(isEmpty(obj1)); // true console.log(isEmpty(obj2)); // false +console.log(isEmpty(childObj)); // true (has no own properties) +console.log(childObj.key); // Output: 'value' (still has the inherited property) ``` ### Edge cases From 8a7e7f14bccdca17f1d12886573212b554045228 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 03:06:12 +0500 Subject: [PATCH 39/56] partial fix: explain-the-concept-of-a-callback-function-in-asynchronous-operations --- .../en-US.mdx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx b/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx index 7ad9a56..947cb7e 100644 --- a/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx +++ b/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx @@ -32,7 +32,7 @@ A callback function is a function that is passed as an argument to another funct ### Example of a synchronous callback -```js +```js live function greet(name, callback) { console.log('Hello ' + name); callback(); @@ -76,13 +76,11 @@ fetchData((data) => { When dealing with asynchronous operations, it's important to handle errors properly. A common pattern is to use the first argument of the callback function to pass an error object, if any. -```js +```js live function fetchData(callback) { - setTimeout(() => { - const error = null; - const data = { name: 'John', age: 30 }; - callback(error, data); - }, 1000); + // assume asynchronous operation to fetch data + const { data, error } = { data: { name: 'John', age: 30 }, error: null }; + callback(error, data); } fetchData((error, data) => { From b961378898182b042f10a0ba6e9361e253676e83 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 03:23:35 +0500 Subject: [PATCH 40/56] partial fix: what-are-promises-and-how-do-they-work --- .../en-US.mdx | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/questions/what-are-promises-and-how-do-they-work/en-US.mdx b/questions/what-are-promises-and-how-do-they-work/en-US.mdx index a9df5ab..bc9b69a 100644 --- a/questions/what-are-promises-and-how-do-they-work/en-US.mdx +++ b/questions/what-are-promises-and-how-do-they-work/en-US.mdx @@ -9,18 +9,21 @@ Promises in JavaScript are objects that represent the eventual completion (or fa ```js let promise = new Promise((resolve, reject) => { // asynchronous operation - if (/* operation successful */) { + const success = true; + if (success) { resolve('Success!'); } else { reject('Error!'); } }); -promise.then(result => { - console.log(result); // 'Success!' -}).catch(error => { - console.error(error); // 'Error!' -}); +promise + .then((result) => { + console.log(result); // 'Success!' (this will print) + }) + .catch((error) => { + console.error(error); // 'Error!' + }); ``` --- @@ -46,7 +49,8 @@ You create a promise using the `Promise` constructor, which takes a function wit ```js let promise = new Promise((resolve, reject) => { // asynchronous operation - if (/* operation successful */) { + const success = true; + if (success) { resolve('Success!'); } else { reject('Error!'); @@ -59,12 +63,22 @@ let promise = new Promise((resolve, reject) => { To handle the result of a promise, you use the `.then()` method for a successful outcome and the `.catch()` method for an error. ```js +let promise = new Promise((resolve, reject) => { + // asynchronous operation + const success = false; + if (success) { + resolve('Success!'); + } else { + reject('Error!'); + } +}); + promise .then((result) => { console.log(result); // 'Success!' }) .catch((error) => { - console.error(error); // 'Error!' + console.error(error); // 'Error!' (this will print) }); ``` From 6bc474adb1b2adb52b1bff4f3208deb89a34f04c Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 03:37:04 +0500 Subject: [PATCH 41/56] partial fix: what-are-callback-functions-and-how-are-they-used --- .../en-US.mdx | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx b/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx index caad021..12c0811 100644 --- a/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx +++ b/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx @@ -6,12 +6,11 @@ title: What are callback functions and how are they used? A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They are commonly used for asynchronous operations like handling events, making API calls, or reading files. For example: -```js +```js live function fetchData(callback) { - setTimeout(() => { - const data = { name: 'John Doe' }; - callback(data); - }, 1000); + // assume an asynchronous operation to fetch data + const data = { name: 'John Doe' }; + callback(data); } function handleData(data) { @@ -33,7 +32,7 @@ A callback function is a function that is passed as an argument to another funct Synchronous callbacks are executed immediately within the function they are passed to. They are often used for tasks that need to be completed before moving on to the next line of code. -```js +```js live function greet(name, callback) { console.log('Hello ' + name); callback(); @@ -44,6 +43,9 @@ function sayGoodbye() { } greet('Alice', sayGoodbye); +// Output: +// Hello Alice +// Goodbye! ``` ### Asynchronous callbacks @@ -105,7 +107,7 @@ function sayHello() { console.log('Hello, world!'); } -setTimeout(sayHello, 2000); +setTimeout(sayHello, 2000); // After 2 seconds elapse, sayHello callback is called ``` ## Further reading From 4235698429ac977afa5729d74f8d9ff9815c4ef6 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 03:41:29 +0500 Subject: [PATCH 42/56] partial fix: explain-the-difference-between-synchronous-and-asynchronous-functions --- .../en-US.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx b/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx index 975d1bd..b79a4a5 100644 --- a/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx +++ b/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the difference between synchronous and asynchronous functions in Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time. -```js +```js live function sum(a, b) { console.log('Inside sum function'); return a + b; @@ -70,7 +70,7 @@ Synchronous functions execute in a sequential order, one after the other. Each o 2. **Looping over large datasets**: Iterating over a large array or dataset synchronously can freeze the user interface or browser tab until the operation completes, leading to an unresponsive application. - ```js + ```js live const largeArray = new Array(1_000_000).fill(0); // Blocks the main thread until the million operations are completed. const result = largeArray.map((num) => num * 2); From 9c4464c59d7b0231654726a607624eb47929fc64 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 17:42:06 +0500 Subject: [PATCH 43/56] exec: explain-how-prototypal-inheritance-works --- .../explain-how-prototypal-inheritance-works/en-US.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/questions/explain-how-prototypal-inheritance-works/en-US.mdx b/questions/explain-how-prototypal-inheritance-works/en-US.mdx index daf074b..6383c26 100644 --- a/questions/explain-how-prototypal-inheritance-works/en-US.mdx +++ b/questions/explain-how-prototypal-inheritance-works/en-US.mdx @@ -12,7 +12,7 @@ This behavior simulates classical inheritance, but it is really more of [delegat Here's an example of prototypal inheritance: -```js +```js live // Parent object constructor. function Animal(name) { this.name = name; @@ -60,7 +60,7 @@ Prototypical inheritance is a feature in JavaScript used to create objects that 1. **Prototypes** : Every object in Javascript has a prototype, which is another object. When you create an object using an object literal or a constructor function, the new object is linked to the prototype of its constructor function or the `Object.prototype` if no prototype is specified. This is commonly referenced using `__proto__` or `[[Prototype]]`. You can also get the prototype by using inbuilt method `Object.getPrototypeOf()` and you can set the prototype of an object via `Object.setPrototypeOf()`. -```js +```js live // Define a constructor function function Person(name, age) { this.name = name; @@ -104,7 +104,7 @@ console.log(john.sayHello); // undefined 3. **Constructor functions**: JavaScript provides constructor functions to create objects. When a function is used as a constructor with the new keyword, the new object's prototype (`[[Prototype]]`) is set to the constructor's prototype property. -```js +```js live // Define a constructor function function Animal(name) { this.name = name; @@ -142,7 +142,7 @@ console.log(fido.fly); // undefined 4. **`Object.create()`**: This method creates a new object with the specified prototype object and properties. It's a straightforward way to set up prototypical inheritance. If you create a object via `Object.create(null)` it will not inherit any properties from `Object.prototype`. This means the object will not have any built-in properties or methods like `toString()`, `hasOwnProperty()`, -```js +```js live // Define a prototype object let proto = { greet: function () { From 3656d64e521a6727abafb1ac5450fb986ba00777 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 17:45:16 +0500 Subject: [PATCH 44/56] exec: explain-the-difference-between-classical-inheritance-and-prototypal-inheritance --- .../en-US.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx b/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx index f31d509..f66e089 100644 --- a/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx +++ b/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx @@ -52,7 +52,7 @@ Prototypal inheritance is a feature of JavaScript where objects inherit directly Example in JavaScript: -```js +```js live const animal = { eat() { console.log('This animal eats food.'); @@ -64,8 +64,8 @@ dog.bark = function () { console.log('The dog barks.'); }; -dog.eat(); // Inherited method -dog.bark(); // Own method +dog.eat(); // Inherited method (Output: The animal eats food.) +dog.bark(); // Own method (Output: The dog barks.) ``` ### Key differences From 38f2a07b041102b9f9a82d9fbdee1da68f1a60c6 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 17:47:16 +0500 Subject: [PATCH 45/56] exec: explain-the-concept-of-inheritance-in-es2015-classes --- .../en-US.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx b/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx index 53b4d4a..67e07a5 100644 --- a/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx +++ b/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the concept of inheritance in ES2015 classes Inheritance in ES2015 classes allows one class to extend another, enabling the child class to inherit properties and methods from the parent class. This is done using the `extends` keyword. The `super` keyword is used to call the constructor and methods of the parent class. Here's a quick example: -```js +```js live class Animal { constructor(name) { this.name = name; @@ -44,7 +44,7 @@ Inheritance in ES2015 classes allows a class (child class) to inherit properties The `extends` keyword is used to create a class that is a child of another class. The child class inherits all the properties and methods of the parent class. -```js +```js live class ParentClass { constructor() { this.parentProperty = 'I am a parent property'; @@ -75,7 +75,7 @@ child.parentMethod(); // This is a parent method The `super` keyword is used to call the constructor of the parent class and to access its methods. This is necessary when you want to initialize the parent class properties in the child class. -```js +```js live class Animal { constructor(name) { this.name = name; @@ -108,7 +108,7 @@ dog.speak(); Child classes can override methods from the parent class. This allows the child class to provide a specific implementation of a method that is already defined in the parent class. -```js +```js live class Animal { speak() { console.log('Animal makes a noise.'); From 7a1b2be1f1b1301da3823c25644590e9ad55933c Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 17:48:22 +0500 Subject: [PATCH 46/56] exec: what-is-the-purpose-of-the-new-keyword --- .../what-is-the-purpose-of-the-new-keyword/en-US.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx b/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx index bd482ff..b17622c 100644 --- a/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx +++ b/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx @@ -6,7 +6,7 @@ title: What is the purpose of the `new` keyword? The `new` keyword in JavaScript is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use `new`, it does four things: it creates a new object, sets the prototype, binds `this` to the new object, and returns the new object. -```js +```js live function Person(name) { this.name = name; } @@ -23,7 +23,7 @@ console.log(person1.name); // Alice The `new` keyword is used to create a new instance of an object. When you call a constructor function with `new`, it creates a new object. -```js +```js live function Car(model) { this.model = model; } @@ -36,7 +36,7 @@ console.log(myCar.model); // Toyota The new object’s internal `[[Prototype]]` property is set to the constructor function’s `prototype` property. This allows the new object to inherit properties and methods from the constructor’s prototype. -```js +```js live function Animal(type) { this.type = type; } @@ -53,7 +53,7 @@ dog.speak(); // Dog makes a sound Inside the constructor function, `this` refers to the new object that is being created. This allows you to add properties and methods to the new object. -```js +```js live function Book(title) { this.title = title; } @@ -66,7 +66,7 @@ console.log(myBook.title); // JavaScript Essentials The `new` keyword implicitly returns the new object created by the constructor function. If the constructor function explicitly returns an object, that object will be returned instead. -```js +```js live function Gadget(name) { this.name = name; return { type: 'Electronic' }; From 4b864fa295c857a37650faeeed29f085aa79622d Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 17:54:12 +0500 Subject: [PATCH 47/56] exec: how-do-you-create-a-constructor-function --- .../en-US.mdx | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/questions/how-do-you-create-a-constructor-function/en-US.mdx b/questions/how-do-you-create-a-constructor-function/en-US.mdx index b1f449a..ce96840 100644 --- a/questions/how-do-you-create-a-constructor-function/en-US.mdx +++ b/questions/how-do-you-create-a-constructor-function/en-US.mdx @@ -6,13 +6,14 @@ title: How do you create a constructor function? To create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the `this` keyword to set properties and methods. When creating an instance, use the `new` keyword. -```js +```js live function Person(name, age) { this.name = name; this.age = age; } const john = new Person('John', 30); +console.log(john.age); // 30 ``` --- @@ -23,7 +24,7 @@ const john = new Person('John', 30); A constructor function in JavaScript is a regular function that is used to create objects. By convention, the name of the constructor function starts with a capital letter to distinguish it from regular functions. -```js +```js live function Person(name, age) { this.name = name; this.age = age; @@ -34,7 +35,7 @@ function Person(name, age) { Within the constructor function, the `this` keyword is used to refer to the object that will be created. Properties and methods can be assigned to `this`. -```js +```js live function Person(name, age) { this.name = name; this.age = age; @@ -50,7 +51,17 @@ function Person(name, age) { To create an instance of the object, use the `new` keyword followed by the constructor function. -```js +```js live +function Person(name, age) { + this.name = name; + this.age = age; + this.greet = function () { + console.log( + `Hello, my name is ${this.name} and I am ${this.age} years old.`, + ); + }; +} + const john = new Person('John', 30); john.greet(); // Output: Hello, my name is John and I am 30 years old. ``` @@ -59,7 +70,7 @@ john.greet(); // Output: Hello, my name is John and I am 30 years old. To save memory, it's a good practice to add methods to the constructor's prototype instead of defining them inside the constructor function. -```js +```js live function Person(name, age) { this.name = name; this.age = age; @@ -77,7 +88,13 @@ jane.greet(); // Output: Hello, my name is Jane and I am 25 years old. You can check if an object is an instance of a constructor function using the `instanceof` operator. -```js +```js live +function Person(name, age) { + this.name = name; + this.age = age; +} +const jane = new Person('Jane', 25); + console.log(jane instanceof Person); // Output: true ``` From 208848a6d6b141fba015b4f9293cde5d6bef22d0 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 19:59:02 +0500 Subject: [PATCH 48/56] exec: what-are-the-differences-between-es6-class-and-es5-function-constructors --- .../en-US.mdx | 95 +++++++++++-------- 1 file changed, 55 insertions(+), 40 deletions(-) diff --git a/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx b/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx index 2fc4420..3948ee6 100644 --- a/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx +++ b/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx @@ -20,28 +20,47 @@ class Person { } ``` -For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do in addition to the above. +For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do. -```js -// ES5 function constructor -function Student(name, studentId) { +```js live +// ES5 inheritance +// Superclass +function Person1(name) { + this.name = name; +} + +// Subclass +function Student1(name, studentId) { // Call constructor of superclass to initialize superclass-derived members. - Person.call(this, name); + Person1.call(this, name); // Initialize subclass's own members. this.studentId = studentId; } +Student1.prototype = Object.create(Person1.prototype); +Student1.prototype.constructor = Student1; -Student.prototype = Object.create(Person.prototype); -Student.prototype.constructor = Student; +const student1 = new Student1('John', 1234); +console.log(student1.name, student1.studentId); // "John" 1234 -// ES2015 Class -class Student extends Person { +// ES2015 inheritance +// Superclass +class Person2 { + constructor(name) { + this.name = name; + } +} + +// Subclass +class Student2 extends Person2 { constructor(name, studentId) { super(name); this.studentId = studentId; } } + +const student2 = new Student2('Alice', 5678); +console.log(student2.name, student2.studentId); // "Alice" 5678 ``` It's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember. @@ -67,7 +86,7 @@ ES5 function constructors and ES2015 classes are two different ways of defining In ES5, you define a class-like structure using a function constructor and prototypes. Here's an example: -```js +```js live // ES5 function constructor function Person(name, age) { this.name = name; @@ -89,7 +108,7 @@ person1.greet(); // Hello, my name is John and I am 30 years old. ES2015 introduced the `class` syntax, which simplifies the definition of classes and supports more features such as static methods and subclassing. Here's the same example using ES2015: -```js +```js live // ES2015 Class class Person { constructor(name, age) { @@ -121,26 +140,26 @@ person1.greet(); // Hello, my name is John and I am 30 years old. - **ES5**: Static methods are added directly to the constructor function. - **ES2015**: Static methods are defined within the class using the `static` keyword. - ```js + ```js live // ES5 - function Person(name, age) { + function Person1(name, age) { this.name = name; this.age = age; } - Person.sayHi = function () { - console.log('Hi!'); + Person1.sayHi = function () { + console.log('Hi from ES5!'); }; - Person.sayHi(); // Hi! + Person1.sayHi(); // Hi from ES5! // ES2015 - class Person { + class Person2 { static sayHi() { - console.log('Hi!'); + console.log('Hi from ES2015!'); } } - Person.sayHi(); // Hi! + Person2.sayHi(); // Hi from ES2015! ``` 3. **Inheritance** @@ -148,45 +167,41 @@ person1.greet(); // Hello, my name is John and I am 30 years old. - **ES5**: Inheritance is achieved using `Object.create()` and manually setting the prototype chain. - **ES2015**: Inheritance is much simpler and more intuitive with the extends keyword. - ```js + ```js live // ES5 Inheritance // ES5 function constructor - function Person(name, age) { + function Person1(name, age) { this.name = name; this.age = age; } - Person.prototype.greet = function () { + Person1.prototype.greet = function () { console.log( - 'Hello, my name is ' + - this.name + - ' and I am ' + - this.age + - ' years old.', + `Hello, my name is ${this.name} and I am ${this.age} years old.`, ); }; - function Student(name, age, grade) { - Person.call(this, name, age); + function Student1(name, age, grade) { + Person1.call(this, name, age); this.grade = grade; } - Student.prototype = Object.create(Person.prototype); - Student.prototype.constructor = Student; + Student1.prototype = Object.create(Person1.prototype); + Student1.prototype.constructor = Student1; - Student.prototype.study = function () { + Student1.prototype.study = function () { console.log(this.name + ' is studying.'); }; - var student1 = new Student('Alice', 20, 'A'); - student1.greet(); // Hello, my name is Alice and I am 20 years old. - student1.study(); // Alice is studying. + var student1 = new Student1('John', 22, 'B+'); + student1.greet(); // Hello, my name is John and I am 22 years old. + student1.study(); // John is studying. // ES2015 Inheritance // ES2015 Class - class Person { + class Person2 { constructor(name, age) { this.name = name; this.age = age; @@ -199,7 +214,7 @@ person1.greet(); // Hello, my name is John and I am 30 years old. } } - class Student extends Person { + class Student2 extends Person2 { constructor(name, age, grade) { super(name, age); this.grade = grade; @@ -210,9 +225,9 @@ person1.greet(); // Hello, my name is John and I am 30 years old. } } - const student1 = new Student('Alice', 20, 'A'); - student1.greet(); // Hello, my name is Alice and I am 20 years old. - student1.study(); // Alice is studying. + const student2 = new Student2('Alice', 20, 'A'); + student2.greet(); // Hello, my name is Alice and I am 20 years old. + student2.study(); // Alice is studying. ``` 4. `super` calls: From ed924732b60ae031acad7142a79a2ae3fa5fb271 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 20:05:27 +0500 Subject: [PATCH 49/56] exec: explain-the-concept-of-lexical-scoping --- questions/explain-the-concept-of-lexical-scoping/en-US.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/questions/explain-the-concept-of-lexical-scoping/en-US.mdx b/questions/explain-the-concept-of-lexical-scoping/en-US.mdx index 444b7af..609d288 100644 --- a/questions/explain-the-concept-of-lexical-scoping/en-US.mdx +++ b/questions/explain-the-concept-of-lexical-scoping/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the concept of lexical scoping Lexical scoping means that the scope of a variable is determined by its location within the source code, and nested functions have access to variables declared in their outer scope. For example: -```js +```js live function outerFunction() { let outerVariable = 'I am outside!'; @@ -36,7 +36,7 @@ When a function is defined, it captures the scope in which it was created. This Consider the following example: -```js +```js live function outerFunction() { let outerVariable = 'I am outside!'; @@ -60,7 +60,7 @@ In this example: Lexical scoping is closely related to closures. A closure is created when a function retains access to its lexical scope, even when the function is executed outside that scope. -```js +```js live function outerFunction() { let outerVariable = 'I am outside!'; From ec002576a4933f4536e9eb11a632333b6b48d799 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 20:28:31 +0500 Subject: [PATCH 50/56] exec: explain-the-concept-of-scope-in-javascript --- .../en-US.mdx | 44 ++++++++++++------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx b/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx index 24e7d94..c693c34 100644 --- a/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx +++ b/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx @@ -6,25 +6,33 @@ title: Explain the concept of scope in JavaScript In JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces `{}`) it is declared. -```js -// Global scope -var globalVar = 'I am global'; +```js live +var globalVar = 'I am a global var'; function myFunction() { - // Function scope - var functionVar = 'I am in a function'; + var functionVar = 'I am a function-scoped var'; if (true) { - // Block scope - let blockVar = 'I am in a block'; - console.log(blockVar); // Accessible here + let blockVar = 'I am a block-scoped var'; + + console.log('Inside block:'); + console.log(globalVar); // Accessible + console.log(functionVar); // Accessible + console.log(blockVar); // Accessible } - // console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined + console.log('Inside function:'); + console.log(globalVar); // Accessible + console.log(functionVar); // Accessible + // console.log(blockVar); // Uncaught ReferenceError } -console.log(globalVar); // Accessible here -// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined +myFunction(); + +console.log('In global scope:'); +console.log(globalVar); // Accessible +// console.log(functionVar); // Uncaught ReferenceError +// console.log(blockVar); // Uncaught ReferenceError ``` --- @@ -35,13 +43,14 @@ console.log(globalVar); // Accessible here Variables declared outside any function or block have global scope. They are accessible from anywhere in the code. -```js +```js live var globalVar = 'I am global'; function myFunction() { console.log(globalVar); // Accessible here } +myFunction(); console.log(globalVar); // Accessible here ``` @@ -49,33 +58,34 @@ console.log(globalVar); // Accessible here Variables declared within a function are in function scope. They are accessible only within that function. -```js +```js live function myFunction() { var functionVar = 'I am in a function'; console.log(functionVar); // Accessible here } -// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined +myFunction(); +console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined ``` ### Block scope Variables declared with `let` or `const` within a block (e.g., within curly braces `{}`) have block scope. They are accessible only within that block. -```js +```js live if (true) { let blockVar = 'I am in a block'; console.log(blockVar); // Accessible here } -// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined +console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined ``` ### Lexical scope JavaScript uses lexical scoping, meaning that the scope of a variable is determined by its location within the source code. Nested functions have access to variables declared in their outer scope. -```js +```js live function outerFunction() { var outerVar = 'I am outside'; From aca559051d91edf5183aaccad630c49bab693f6f Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 20:30:23 +0500 Subject: [PATCH 51/56] exec: how-can-closures-be-used-to-create-private-variables --- .../en-US.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx b/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx index d65a711..26e9f45 100644 --- a/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx +++ b/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx @@ -6,7 +6,7 @@ title: How can closures be used to create private variables? Closures in JavaScript can be used to create private variables by defining a function within another function. The inner function has access to the outer function's variables, but those variables are not accessible from outside the outer function. This allows you to encapsulate and protect the variables from being accessed or modified directly. -```js +```js live function createCounter() { let count = 0; // private variable @@ -51,7 +51,7 @@ To create private variables using closures, you can define a function that retur Here's a detailed example to illustrate how closures can be used to create private variables: -```js +```js live function createCounter() { let count = 0; // private variable From 14f54cf115d14d987eba9528e0635f5b9e1674d1 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Fri, 7 Mar 2025 20:35:24 +0500 Subject: [PATCH 52/56] exec: explain-the-difference-between-global-scope-function-scope-and-block-scope --- .../en-US.mdx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx b/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx index 25eac18..d4c8598 100644 --- a/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx +++ b/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx @@ -6,7 +6,7 @@ title: Explain the difference between global scope, function scope, and block sc Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within `{}`) they are declared in. -```js +```js live var globalVar = "I'm global"; // Global scope function myFunction() { @@ -18,6 +18,7 @@ function myFunction() { // console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined } // console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined +myFunction(); ``` --- @@ -28,7 +29,7 @@ function myFunction() { Variables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the `window` object. -```js +```js live var globalVar = "I'm global"; function checkGlobal() { @@ -43,21 +44,21 @@ console.log(globalVar); // Output: "I'm global" Variables declared within a function are only accessible within that function. This is true for variables declared using `var`, `let`, or `const`. -```js +```js live function myFunction() { var functionVar = "I'm in a function"; console.log(functionVar); // Accessible here } myFunction(); // Output: "I'm in a function" -// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined +console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined ``` ### Block scope Variables declared with `let` or `const` within a block (e.g., within `{}`) are only accessible within that block. This is not true for `var`, which is function-scoped. -```js +```js live if (true) { let blockVar = "I'm in a block"; console.log(blockVar); // Accessible here From 0596b5c20ee88e1e5287ddd2764ad930148814e6 Mon Sep 17 00:00:00 2001 From: tahachm <97478750+tahachm@users.noreply.github.com> Date: Sat, 8 Mar 2025 01:40:03 +0500 Subject: [PATCH 53/56] partial fix: what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor --- .../en-US.mdx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx b/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx index 91c7ba0..70974f7 100644 --- a/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx +++ b/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx @@ -8,7 +8,7 @@ The main advantage of using an arrow function as a method inside a constructor i For example, let's say we have a `Person` constructor that takes a first name as an argument has two methods to `console.log()` that name, one as a regular function and one as an arrow function: -```js +```js live const Person = function (name) { this.name = name; this.sayName1 = function () { @@ -68,12 +68,14 @@ const myFunction = (arg1, arg2, ...argN) => expression; ### Examples -```js +```js live // Arrow function with parameters const multiply = (x, y) => x * y; +console.log(multiply(2, 3)); // Output: 6 // Arrow function with no parameters const sayHello = () => 'Hello, World!'; +console.log(sayHello()); // Output: 'Hello, World!' ``` ### Advantages @@ -86,7 +88,7 @@ const sayHello = () => 'Hello, World!'; Arrow functions cannot be used as constructors and will throw an error when used with the `new` keyword. -```js +```js live const Foo = () => {}; const foo = new Foo(); // TypeError: Foo is not a constructor ``` @@ -104,7 +106,7 @@ arrowFunction(1, 2, 3); Since arrow functions do not have their own `this`, they are not suitable for defining methods in an object. Traditional function expressions or function declarations should be used instead. -```js +```js live const obj = { value: 42, getValue: () => this.value, // `this` does not refer to `obj` @@ -119,7 +121,7 @@ One of the most notable features of arrow functions is their behavior with `this ### Arrow functions inside function constructors -```js +```js live const Person = function (name) { this.name = name; this.sayName1 = function () { From 9925c12f879b6147fdc0d54b31b7b8355d2472d6 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Fri, 7 Mar 2025 20:50:20 +0000 Subject: [PATCH 54/56] [auto] regenerate table of contents --- README.md | 259 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 161 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index 9647747..2eeef05 100644 --- a/README.md +++ b/README.md @@ -550,7 +550,7 @@ Here's a table summarizing the 3 ways of loading `