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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] [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() {