From 26dfb0e2114d20a972b95f886edde0522303392e Mon Sep 17 00:00:00 2001 From: onrails Date: Sun, 4 Sep 2022 21:02:27 +0100 Subject: [PATCH 01/82] fix: trim method output correction for #Q 6.3. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 868ce25..29246d9 100644 --- a/README.md +++ b/README.md @@ -1712,7 +1712,7 @@ const name = " Karan Talwar "; console.log(name.trim()); // => 'Karan Talwar' const phoneNumber = "\t 80-555-123\n "; -console.log(phoneNumber.trim()); // => '555-123' +console.log(phoneNumber.trim()); // => '80-555-123' ``` **2. string.trimStart():** From 1e0ece037043a7f6845d8b853acb37e76b15757b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 18 Sep 2022 10:50:37 +0530 Subject: [PATCH 02/82] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 29246d9..1d59254 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ ## Related Interview Questions +* [HTML5 Interview Questions](https://github.com/learning-zone/html-interview-questions) +* [CSS Interview Questions](https://github.com/learning-zone/css-interview-questions) * [JavaScript ES6 Basics](https://github.com/learning-zone/JavaScript-ES6-Basics/blob/main/README.md) * [JavaScript Design Patterns](https://github.com/learning-zone/JavaScript-Design-Patterns/blob/main/README.md) * [JavaScript Coding Practice](https://github.com/learning-zone/JavaScript-Coding-Practice/blob/main/README.md) From 948c88ba0ab1df8620ca8f8961c4f00001deae75 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 18 Sep 2022 10:51:32 +0530 Subject: [PATCH 03/82] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1d59254..68d7d78 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ * [HTML5 Interview Questions](https://github.com/learning-zone/html-interview-questions) * [CSS Interview Questions](https://github.com/learning-zone/css-interview-questions) -* [JavaScript ES6 Basics](https://github.com/learning-zone/JavaScript-ES6-Basics/blob/main/README.md) -* [JavaScript Design Patterns](https://github.com/learning-zone/JavaScript-Design-Patterns/blob/main/README.md) -* [JavaScript Coding Practice](https://github.com/learning-zone/JavaScript-Coding-Practice/blob/main/README.md) +* [JavaScript ES6 Basics](https://github.com/learning-zone/JavaScript-ES6-Basics) +* [JavaScript Design Patterns](https://github.com/learning-zone/JavaScript-Design-Patterns) +* [JavaScript Coding Practice](https://github.com/learning-zone/JavaScript-Coding-Practice)
From dde96d4b92e6eee7be6f9c289cf0c2ba236b334f Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 24 Sep 2022 11:18:50 +0530 Subject: [PATCH 04/82] Update README.md --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 68d7d78..f697b03 100644 --- a/README.md +++ b/README.md @@ -1180,11 +1180,11 @@ JavaScript provides comparison operators that compare two operands and return a The logical operators are used to combine two or more conditions. -|Operators |Description | -|----------|--------------------| -|&& && |is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null or "" are considered as zero). It returns 1 if they are non-zero; otherwise, returns 0.| -||| | || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false, undefined, null or "" is considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0.| -|! | ! is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true, and !true returns false.| +**1. &&** - is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null or "" are considered as zero). It returns 1 if they are non-zero; otherwise, returns 0 + +**2. ||** - is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false, undefined, null or "" is considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0. + +**3. !** - is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true, and !true returns false. **Assignment Operators:** From b8919a04274c3d90765f18df4260f62fb2508b5b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 24 Sep 2022 11:48:18 +0530 Subject: [PATCH 05/82] Update README.md --- README.md | 42 +++++++++++++----------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index f697b03..203a75e 100644 --- a/README.md +++ b/README.md @@ -3063,43 +3063,29 @@ sayNameFromWindow2(); // John ## Q 9.3. Difference between `Function`, `Method` and `Constructor` calls in JavaScript? -If your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct. - -functions : The simplest usages of function call: +**1. Functions:** The simplest usages of function call: ```js -function helloWorld(name) { - return "hello world, " + name; +function display(name) { + return "Hello " + name; } -helloWorld("JS Geeks"); // "hello world JS Geeks" +display("World"); // "Hello World" ``` -Methods in JavaScript are nothing more than object properties that are functions. +**2. Methods:** in JavaScript are nothing more than object properties that are functions. ```js var obj = { - helloWorld : function() { - return "hello world, " + this.name; + display : function() { + return "Hello " + this.name; }, - name: 'John Carter' -} -obj.helloWorld(); // // "hello world John Carter" -``` - -Notice how `helloWorld` refer to `this` properties of obj. Here It is clear or you might have already understood that `this` gets bound to `obj`. But the interesting point that we can copy a reference to the same function `helloWorld` in another object and get a difference answer. Let see: - -```js -var obj2 = { - helloWorld : obj.helloWorld, - name: 'John Doe' + name: 'Minali Peri' } -obj2.helloWorld(); // "hello world John Doe" +obj.display(); // "Hello Minali Peri" ``` -You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this `this`, The expression `obj2.helloWorld()` looks up the `helloWorld` property of obj and calls it with receiver object `obj2`. - -The third use of functions is as constructors. Like function and method, `constructors` are defined with function. +**3. Constructors:** Like function and method, `constructors` are defined with function. ```js function Employee(name, age) { @@ -3107,14 +3093,12 @@ function Employee(name, age) { this.age = age; } -var emp1 = new Employee('John Doe', 28); -emp1.name; // "John Doe" +var emp1 = new Employee('Drishya Sama', 28); +emp1.name; // "Drishya Sama" emp1.age; // 28 ``` -Unlike function calls and method calls, a constructor call `new Employee('John Doe', 28)` creates a brand new object and passes it as the value of `this`, and implicitly returns the new object as its result. - -The primary role of the constructor function is to initialize the object. +Unlike function calls and method calls, a constructor call `new Employee('Drishya Sama', 28)` creates a new object and passes it as the value of `this`, and implicitly returns the new object as its result. The primary role of the constructor function is to initialize the object.
↥ back to top From efe80424d2d732a0e3df9165181c4e4c55511780 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 24 Sep 2022 11:54:20 +0530 Subject: [PATCH 06/82] Update README.md --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 203a75e..9405eae 100644 --- a/README.md +++ b/README.md @@ -3499,11 +3499,9 @@ console.log(fun2.length); // 2 ## Q 9.14. What is the difference between Call, Apply and Bind? -* **Call** invokes the function and allows you to pass in arguments one by one. -* **Apply** invokes the function and allows you to pass in arguments as an array. -* **Bind** returns a new function, allowing you to pass in a this array and any number of arguments. +**1. Call:** invokes the function and allows you to pass in arguments one by one. -**Example:** `call()` +**Example:** ```js const employee1 = { firstName: "Sahima", lastName: "Mutti" }; @@ -3517,7 +3515,9 @@ say.call(employee1, "Hi"); // Hi Sahima Mutti say.call(employee2, "Hello"); // Hello Aarush Krishna ``` -**Example:** `apply()` +**2. Apply:** invokes the function and allows you to pass in arguments as an array. + +**Example:** ```js const employee1 = { firstName: "Sahima", lastName: "Mutti" }; @@ -3531,7 +3531,9 @@ say.apply(employee1, ["Hi"]); // Hi Sahima Mutti say.apply(employee2, ["Hello"]); // Hello Aarush Krishna ``` -**Example:** `bind()` +**3. Bind:** returns a new function, allowing you to pass in a this array and any number of arguments. + +**Example:** ```js const employee1 = { firstName: "Sahima", lastName: "Mutti" }; From be1a90f0bc6b3d7ba5d92e9fdd6d473f37214ba8 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 24 Sep 2022 11:56:19 +0530 Subject: [PATCH 07/82] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9405eae..0029d19 100644 --- a/README.md +++ b/README.md @@ -3563,8 +3563,9 @@ The `bind()` method creates a new function, when invoked, has the `this` sets to **Example:** ```js -// bind() function - +/** + * bind() function + */ const person = { firstName: "Chhavi", lastName: "Goswami", From 7d276e971241f453675f4ee1d9cd4ab6478d25dc Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 25 Sep 2022 08:44:08 +0530 Subject: [PATCH 08/82] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0029d19..23df257 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ * [JavaScript ES6 Basics](https://github.com/learning-zone/JavaScript-ES6-Basics) * [JavaScript Design Patterns](https://github.com/learning-zone/JavaScript-Design-Patterns) * [JavaScript Coding Practice](https://github.com/learning-zone/JavaScript-Coding-Practice) +* [JavaScript Unit Testing](https://github.com/learning-zone/js-unit-testing-interview-questions)
From 7e4ee801e81cd478d52ca7d72e0b23502c8372ea Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 11:00:03 +0530 Subject: [PATCH 09/82] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 23df257..2fb2ef7 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Template literals are string literals allowing embedded expressions. ```js // String Substitution let name = `Abhinav Sharma`; -console.log(`Hi, ${name}!`); // Output: "Abhinav Sharma" +console.log(`Hi, ${name}`); // Output: "Abhinav Sharma" // Multiline String let msg = `Hello \ @@ -83,11 +83,11 @@ function sum(x, y, z) { } const numbers = [10, 20, 30]; -// Using Spread Operator -console.log(sum(...numbers)); // 60 - // Using Apply (ES5) console.log(sum.apply(null, numbers)); // 60 + +// Using Spread Operator +console.log(sum(...numbers)); // 60 ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-spread-operator-25tmcf?file=/src/index.js)** @@ -105,7 +105,7 @@ let newFruitArray = [...fruits]; console.log(newFruitArray); //Output -['Apple','Orange','Banana'] +['Apple', 'Orange', 'Banana'] ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-spread-operator-wy1q0l?file=/src/index.js)** @@ -144,7 +144,7 @@ let newFruits = ["Cherry", ...fruits]; console.log(newFruits); // Output -['Cherry', 'Apple','Orange','Banana'] +['Cherry', 'Apple', 'Orange', 'Banana'] ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-spread-operator-16l7oh?file=/src/index.js)** From 70199b3d9386aeed4bc7b3de0605e52a6a0373b2 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 11:21:36 +0530 Subject: [PATCH 10/82] Update README.md --- README.md | 93 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 2fb2ef7..8af96d9 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,11 @@ let fruits = ["Apple", "Orange", "Banana"]; let newFruitArray = [...fruits]; console.log(newFruitArray); +``` + +Output: -//Output +```js ['Apple', 'Orange', 'Banana'] ``` @@ -123,8 +126,11 @@ let arr2 = ["X", "Y", "Z"]; let result = [...arr1, ...arr2]; console.log(result); +``` -// Output +Output: + +```js ['A', 'B', 'C', 'X', 'Y', 'Z'] ``` @@ -138,12 +144,14 @@ console.log(result); ```js let fruits = ["Apple", "Orange", "Banana"]; - let newFruits = ["Cherry", ...fruits]; console.log(newFruits); +``` -// Output +Output: + +```js ['Cherry', 'Apple', 'Orange', 'Banana'] ``` @@ -163,8 +171,11 @@ const getFruits = (f1, f2, f3) => { }; getFruits(...fruits); +``` -// Output +Output: + +```js Fruits: Apple, Orange and Banana ``` @@ -178,7 +189,7 @@ Fruits: Apple, Orange and Banana ```js var obj1 = { id: 101, name: 'Rajiv Sandal' } -var obj2 = { age: 35, country: 'INDIA'} +var obj2 = { age: 35, country: 'INDIA' } const employee = { ...obj1, ...obj2 } @@ -230,8 +241,11 @@ The `repeat()` method constructs and returns a new string which contains the spe const msg = "Hello World \n"; console.log(`${msg.repeat(3)}`); +``` -// Output: +Output: + +```js Hello World Hello World Hello World @@ -260,30 +274,12 @@ console.log(add(10, 20)); // 30 **7. Arrow function with `this`** ```js -/** - * Using ES5 - * - **/ -var person = { - name: "Diksha", - actions: ["bike", "hike", "ski", "surf"], - printActions: function() { - var _this = this; - this.actions.forEach(function(action) { - var str = _this.name + " likes to " + action; - console.log(str); - }); - } -}; -person.printActions(); - /** * Using Arrow function - * - **/ + */ let person = { name: "Diksha", - actions: ["bike", "hike", "ski", "surf"], + actions: ["bike", "hike", "ski"], printActions() { this.actions.forEach((action) => { let str = this.name + " likes to " + action; @@ -293,12 +289,14 @@ let person = { }; person.printActions(); +``` + +Output: -// Output: +```js Diksha likes to bike Diksha likes to hike -Diksha likes to ski -Diksha likes to surf +Diksha likes to ski ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-arrow-function-kh1v84?file=/src/index.js)** @@ -498,8 +496,7 @@ Variables declared using the `var` keyword are scoped to the function in which t ```js /** * All variables are accessible within functions. - * -**/ + */ function variableScope() { var x = 10; @@ -521,8 +518,7 @@ variableScope(); ```js /** * var declared variables are accessible anywhere in the function scope. - * - **/ + */ if (true) { var a = 10; let b = 20; @@ -592,8 +588,11 @@ getName("Sadhika Sandal"); function getName(name) { console.log("Hello " + name); } +``` -// Output +Output: + +```js Hello Sadhika Sandal ``` @@ -638,9 +637,9 @@ They will only get initialized when their lexical binding (assignment) is evalua Let us take the following **function expression** ```js - var foo = function foo() { - return 12; - } +var foo = function foo() { + return 12; +} ``` In JavaScript `var`-declared variables and functions are `hoisted`. Let us take function `hoisting` first. Basically, the JavaScript interpreter looks ahead to find all the variable declaration and hoists them to the top of the function where It is declared. For example: @@ -676,11 +675,14 @@ foo(); // Now foo is defined here ## Q 2.6. What is the Temporal Dead Zone in ES6? -In ES6, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a `ReferenceError` (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed. +In ES6, **let** bindings are not subject to Variable Hoisting, which means that **let** declarations do not move to the top of the current execution context. -```javascript +Referencing the variable in the block before the initialization results in a `ReferenceError` (contrary to a variable declared with var, which will just have the **undefined** value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed. + +```js console.log(aVar); // undefined console.log(aLet); // causes ReferenceError: aLet is not defined + var aVar = 1; let aLet = 2; ``` @@ -803,7 +805,9 @@ console.log(x) // 1 ## Q 2.9. How do you assign default values to variables? -You can use the logical or operator `||` in an assignment expression to provide a default value. The syntax looks like as below, +You can use the logical or operator `||` in an assignment expression to provide a default value. + +**Syntax:** ```js var a = b || c; @@ -817,7 +821,7 @@ As per the above expression, variable 'a 'will get the value of 'c' only if 'b' ## Q 2.10. What is the precedence order between local and global variables? -A local variable takes precedence over a global variable with the same name. +A local variable takes precedence over a global variable with the same name. ```js var msg = "Good morning"; @@ -827,8 +831,11 @@ function greeting() { console.log(msg); } greeting(); +``` -// Output +Output: + +```js Good Evening ``` From ba75847a124d21f2d9db557806cfcd091db72323 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 11:44:34 +0530 Subject: [PATCH 11/82] Update README.md --- README.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/README.md b/README.md index 8af96d9..2bf5dc2 100644 --- a/README.md +++ b/README.md @@ -308,20 +308,13 @@ Diksha likes to ski **8. Destructing Assignment:** ```js -const phone = { - title: "iPhone", - price: 999, - description: "The iPhone is a smartphone developed by Apple" -}; -console.log(phone.title); - - // Destructing Assignment const { title, price, description } = { title: "iPhone", price: 999, description: "The iPhone is a smartphone developed by Apple" }; + console.log(title); // iPhone console.log(price); // 999 console.log(description); // The iPhone is a smartphone developed by Apple From 90c95eafdb09e6ee25feed75d18895d61284c406 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 12:26:48 +0530 Subject: [PATCH 12/82] Update README.md --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2bf5dc2..8069a3e 100644 --- a/README.md +++ b/README.md @@ -668,7 +668,7 @@ foo(); // Now foo is defined here ## Q 2.6. What is the Temporal Dead Zone in ES6? -In ES6, **let** bindings are not subject to Variable Hoisting, which means that **let** declarations do not move to the top of the current execution context. +In ES6, **let** bindings are not subject to "variable hoisting", which means that **let** declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a `ReferenceError` (contrary to a variable declared with var, which will just have the **undefined** value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed. @@ -845,15 +845,15 @@ Variable shadowing occurs when a variable declared within a certain scope (decis If there is a variable in the global scope, and you'd like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope. ```js +/** + * Variable Shadowing + */ var val = 10; function Hoist(val) { console.log(val); } -Hoist(20); - -// Output: -20 +Hoist(20); // 20 ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-variable-shadowing-dvibcw?file=/src/index.js)** From 23b47381497c284ab3f15c11fc9794e18d35a8a3 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 12:27:12 +0530 Subject: [PATCH 13/82] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8069a3e..f231639 100644 --- a/README.md +++ b/README.md @@ -844,6 +844,8 @@ Variable shadowing occurs when a variable declared within a certain scope (decis If there is a variable in the global scope, and you'd like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope. +**Example:** + ```js /** * Variable Shadowing From 8bb2a88f2cfd16a7f68f8a14704f8d2ffdb17114 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 15:22:08 +0530 Subject: [PATCH 14/82] Update README.md --- README.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f231639..24e203e 100644 --- a/README.md +++ b/README.md @@ -866,12 +866,16 @@ Hoist(20); // 20 ## Q 2.12. Explain `var self = this` in JavaScript? -`self` is being used to maintain a reference to the original this even as the context is changing. It is a technique often used in event handlers (especially in closures). +The **self** is being used to maintain a reference to the original this even as the context is changing. It is a technique often used in event handlers ( especially in closures ). -`this` is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping(in C open/close {} curly braces refers to a block). JavaScript has two scopes namely, global and local scope. +`this` is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping ( in C open/close {} curly braces refers to a block ). JavaScript has two scopes namely, global and local scope. + +**Example:** ```js -// this Context +/** + * this Context + */ const context = { prop: 10, getCurrentContext: function () { @@ -879,8 +883,7 @@ const context = { } }; -console.log(context.getCurrentContext()); -// expected output: 10 +console.log(context.getCurrentContext()); // 10 ``` *Note: 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.* @@ -1587,7 +1590,11 @@ Number.NEGATIVE_INFINITY * The value of negative infinity is the same as the negative value of the infinity property of the global object. ```js -// NEGATIVE_INFINITY +/** + * NEGATIVE_INFINITY + */ + +console.log(-10/0); // -Infinity console.log(Number.NEGATIVE_INFINITY); // -Infinity console.log(Number.MAX_VALUE + Number.MAX_VALUE); // Infinity console.log(-2 * Number.MAX_VALUE); // -Infinity From 7a11a51da15366981d5eea99ac008c770e7d2f16 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 15:51:53 +0530 Subject: [PATCH 15/82] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 24e203e..1253d97 100644 --- a/README.md +++ b/README.md @@ -3468,7 +3468,9 @@ The arguments object is an Array-like object ( `arguments` ) accessible inside f **Example:** ```js -// arguments object +/** + * Arguments Object + */ function sum() { let total = 0; From 4a293b65bf8b3d57faf31c90f71d43e9fd0fe5cc Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 31 Oct 2022 15:23:17 +0530 Subject: [PATCH 16/82] Update README.md --- README.md | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 1253d97..d36e388 100644 --- a/README.md +++ b/README.md @@ -519,44 +519,46 @@ if (true) { } console.log(a); // 10 -console.log(b); // ReferenceError: baz is not defined -console.log(c); // ReferenceError: qux is not defined +console.log(b); // ReferenceError: b is not defined +console.log(c); // ReferenceError: c is not defined ``` `var` allows variables to be hoisted, meaning they can be referenced in code before they are declared. `let` and `const` will not allow this, instead throwing an error. ```js -console.log(foo); // undefined -var foo = 'foo'; +console.log(a); // undefined +var a = 'foo'; -console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization -let baz = 'baz'; +console.log(b); // ReferenceError: can't access lexical declaration 'b' before initialization +let b = 'baz'; -console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization -const bar = 'bar'; +console.log(c); // ReferenceError: can't access lexical declaration 'c' before initialization +const c = 'bar'; ``` Redeclaring a variable with `var` will not throw an error, but 'let' and 'const' will. ```js -var foo = 'foo'; -var foo = 'bar'; -console.log(foo); // "bar" +var a = 'foo'; +var a = 'bar'; +console.log(a); // "bar" -let baz = 'baz'; -let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared +let b = 'baz'; +let b = 'qux'; // Uncaught SyntaxError: Identifier 'b' has already been declared ``` `let` and `const` differ in that `let` allows reassigning the variable's value while `const` does not. ```js -// This is fine. -let foo = 'foo'; -foo = 'bar'; +// This is ok. +let a = 'foo'; +a = 'bar'; +console.log(a); // bar // This causes an exception. -const baz = 'baz'; -baz = 'qux'; +const b = 'baz'; +b = 'qux'; +console.log(b) // TypeError: Assignment to constant variable. ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-variables-declaration-fmrkjz?file=/src/index.js)** From 5036f8ca8e98182340f1cce751292bf0c74f0dfe Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 31 Oct 2022 16:01:53 +0530 Subject: [PATCH 17/82] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index d36e388..1fe4c29 100644 --- a/README.md +++ b/README.md @@ -2668,6 +2668,14 @@ SyntaxError: Rest element must be last element ↥ back to top
+## Q 7.20. What is difference between [] and new Array()? + +*ToDo* + + + ## # 8. Regular Expression
From a71ebd2e13d874e8fb2bb17903e12acc46ec79b1 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 31 Oct 2022 16:08:56 +0530 Subject: [PATCH 18/82] Update README.md --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1fe4c29..58eac6f 100644 --- a/README.md +++ b/README.md @@ -5853,7 +5853,7 @@ console.log(Object.keys(user)); //['name', 'gender', 'age'] ↥ back to top -## Q 11.32. What is difference between array[] vs object()? +## Q 11.32. What is difference between array[] vs Object()? * `[]` is declaring an array. * `{}` is declaring an object. @@ -5880,6 +5880,14 @@ An array is an object so it has all the same capabilities of an object plus a bu ↥ back to top +## Q 11.33. What is difference between `{}` vs `new Object()`? + +*ToDo* + + + # # 12. WINDOW AND DOCUMENT OBJECT
From 0664e69b884e7634528c9c295187b43b7572e737 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 4 Nov 2022 10:52:47 +0530 Subject: [PATCH 19/82] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 58eac6f..06cac1f 100644 --- a/README.md +++ b/README.md @@ -7837,6 +7837,14 @@ The `XMLHTTPRequest()` object is an API which is used for fetching data from the |statusText |Returns the status-text (e.g. "OK" or "Not Found")| + + +## Q. 15.14. How to get responses of multiple api calls, when some API fails? + +*ToDo* + From 44a3d10c1badcdf68dfdb85222c8aabb94d3784e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 4 Nov 2022 11:55:22 +0530 Subject: [PATCH 20/82] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 06cac1f..cf9fa95 100644 --- a/README.md +++ b/README.md @@ -7849,6 +7849,14 @@ The `XMLHTTPRequest()` object is an API which is used for fetching data from the ↥ back to top +## Q. 15.15. Explain the use of Promise.any()? + +*ToDo* + + + ## # 16. Collections
From 024928fb7eda789f90f1fd972ee9f9528f5bf35a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 19:38:04 +0530 Subject: [PATCH 21/82] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cf9fa95..c6c7b5f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# JavaScript Interview Questions ( vES6 ) +# JavaScript Basics ( vES6 ) *Click if you like the project. Pull Request are highly appreciated.*
-## Related Interview Questions +## Related Topics * [HTML5 Interview Questions](https://github.com/learning-zone/html-interview-questions) * [CSS Interview Questions](https://github.com/learning-zone/css-interview-questions) From 54dc8f46d3a671ef87f049a9b4a8a75923ace71a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 20:36:33 +0530 Subject: [PATCH 22/82] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c6c7b5f..dad1158 100644 --- a/README.md +++ b/README.md @@ -6,12 +6,12 @@ ## Related Topics -* [HTML5 Interview Questions](https://github.com/learning-zone/html-interview-questions) -* [CSS Interview Questions](https://github.com/learning-zone/css-interview-questions) -* [JavaScript ES6 Basics](https://github.com/learning-zone/JavaScript-ES6-Basics) -* [JavaScript Design Patterns](https://github.com/learning-zone/JavaScript-Design-Patterns) -* [JavaScript Coding Practice](https://github.com/learning-zone/JavaScript-Coding-Practice) -* [JavaScript Unit Testing](https://github.com/learning-zone/js-unit-testing-interview-questions) +* [HTML5 Basics](https://github.com/learning-zone/html-basics) +* [CSS Basics](https://github.com/learning-zone/css-basics) +* [JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics) +* [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) +* [JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice) +* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing-basics)
From c03a9bbb9c9b8003dc3c3c57836f2645073e4c06 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 20:37:15 +0530 Subject: [PATCH 23/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dad1158..9449b05 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## Related Topics -* [HTML5 Basics](https://github.com/learning-zone/html-basics) +* [HTML Basics](https://github.com/learning-zone/html-basics) * [CSS Basics](https://github.com/learning-zone/css-basics) * [JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics) * [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) From b67a90ba72a85965a4ca873108afb6042673503a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 20:38:11 +0530 Subject: [PATCH 24/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9449b05..179aee2 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ * [JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics) * [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) * [JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice) -* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing-basics) +* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing)
From 82a1135f1ffd3c187fd8c4a549b369c3aba72a5a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 20:38:58 +0530 Subject: [PATCH 25/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 179aee2..2852e6d 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ * [HTML Basics](https://github.com/learning-zone/html-basics) * [CSS Basics](https://github.com/learning-zone/css-basics) * [JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics) +* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing) * [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) * [JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice) -* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing)
From df530624b806d1aba5a28550fcbad3964a62e32f Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 08:27:19 +0530 Subject: [PATCH 26/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2852e6d..19b65d3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# JavaScript Basics ( vES6 ) +# JavaScript Basics *Click if you like the project. Pull Request are highly appreciated.* From 9094602840902ac492961eaaa7ad73d0a37ea6b0 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 19 Nov 2022 08:20:26 +0530 Subject: [PATCH 27/82] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 19b65d3..8b28ee5 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ * [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing) * [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) * [JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice) +* [Data Structure in JavaScript](https://github.com/learning-zone/javascript-data-structure)
From a341bb0109d4f237851042b8061576b701b19933 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 21 Nov 2022 10:33:17 +0530 Subject: [PATCH 28/82] Update README.md --- README.md | 29 ++--------------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 8b28ee5..b7cd2a4 100644 --- a/README.md +++ b/README.md @@ -1437,32 +1437,7 @@ function getValue(someParam) { ↥ back to top -## Q 4.9. What is the difference between `==` and `===`? - -The `==` is the abstract equality operator while `===` is the strict equality operator. The `==` operator will compare for equality after doing any necessary type conversions. - -The `===` operator will not do type conversion, so if two values are not the same type `===` will simply return `false`. When using `==`, funky things can happen, such as: - -```js -1 == '1'; // true -1 == [1]; // true -1 == true; // true -0 == ''; // true -0 == '0'; // true -0 == false; // true - -let x = null; -console.log(x == null); // true -console.log(x == undefined); // true -``` - -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-equality-operator-lt2ngc?file=/src/index.js)** - - - -## Q 4.10. What is the difference between `typeof` and `instanceof` operator? +## Q 4.9. What is the difference between `typeof` and `instanceof` operator? The `typeof` operator checks if a value has type of primitive type which can be one of boolean, function, object, number, string, undefined and symbol (ES6). @@ -1492,7 +1467,7 @@ b instanceof String; // returns true ↥ back to top -## Q 4.11. What is the output of below spread operator array? +## Q 4.10. What is the output of below spread operator array? ```js [...'Hello'] From 036da264472b1524820fca514709f8b3e0b4f21e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 29 Nov 2022 16:54:33 +0530 Subject: [PATCH 29/82] Update README.md --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b7cd2a4..0182a23 100644 --- a/README.md +++ b/README.md @@ -9030,8 +9030,13 @@ All Chromium-based browsers use Blink, as do applications built with CEF, Electr Microsoft formerly developed its own proprietary browser engines - Trident and EdgeHTML, though now uses Blink for its Edge browser. -#### Q 18.22. What is optional chaining in javascript? -#### Q 18.23. How could you make sure a const value is garbage collected? + + +#### Q 18.22. What is a Polyfill? +#### Q 18.23. What is optional chaining in javascript? +#### Q 18.24. How could you make sure a const value is garbage collected? *ToDo* From 017586cb85eb7cceb6d7c8b88dcb78f47266ca1a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 29 Nov 2022 20:03:15 +0530 Subject: [PATCH 30/82] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0182a23..17b54b3 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,13 @@ ## Related Topics -* [HTML Basics](https://github.com/learning-zone/html-basics) -* [CSS Basics](https://github.com/learning-zone/css-basics) -* [JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics) -* [JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing) -* [JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns) -* [JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice) -* [Data Structure in JavaScript](https://github.com/learning-zone/javascript-data-structure) +* *[HTML Basics](https://github.com/learning-zone/html-basics)* +* *[CSS Basics](https://github.com/learning-zone/css-basics)* +* *[JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics)* +* *[JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing)* +* *[JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns)* +* *[JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice)* +* *[Data Structure in JavaScript](https://github.com/learning-zone/javascript-data-structure)*
From 6c74597dab6b335e2bbd5c13cf477de1ecc81c64 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 29 Nov 2022 20:18:39 +0530 Subject: [PATCH 31/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 17b54b3..9138ac0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # JavaScript Basics -*Click if you like the project. Pull Request are highly appreciated.* +> *Click if you like the project. Your contributions are heartily ♡ welcome.*
From ed06b6035e040c9c6ace965c241a5fbbcb968868 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 30 Nov 2022 09:45:12 +0530 Subject: [PATCH 32/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9138ac0..9c82d5d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # JavaScript Basics -> *Click if you like the project. Your contributions are heartily ♡ welcome.* +> *Click ★ if you like the project. Your contributions are heartily ♡ welcome.*
From bb4926401f6b05e7d1b2fad69b3e849298b37ead Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 6 Dec 2022 16:15:43 +0530 Subject: [PATCH 33/82] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 9c82d5d..bbc3cee 100644 --- a/README.md +++ b/README.md @@ -914,6 +914,14 @@ console.log(y); // 10 ↥ back to top +## Q 2.14. What is scope chain in javascript? + +*ToDo* + + + ## # 3. DATA TYPES
From 8b588800a20109c596ec641d841b9cb577b0b297 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 6 Dec 2022 16:16:46 +0530 Subject: [PATCH 34/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbc3cee..467fdbd 100644 --- a/README.md +++ b/README.md @@ -897,7 +897,7 @@ console.log(context.getCurrentContext()); // 10 ↥ back to top -## Q 2.13. How do you swap variables using Destructuring Assignment? +## Q 2.13. How do you swap variables using destructuring assignment? ```js var x = 10, y = 20; From d10c2e1e6334e901c8943446cc29a361c523551d Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 7 Dec 2022 14:52:55 +0530 Subject: [PATCH 35/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 467fdbd..02c6528 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@
-## Table of Contents +## Contents * [Introduction](#-1-introduction) * [Variables](#-2-variables) From 38c3e097eb799a8a1c0056484cf8aff2c0740807 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 7 Dec 2022 15:04:38 +0530 Subject: [PATCH 36/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02c6528..467fdbd 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@
-## Contents +## Table of Contents * [Introduction](#-1-introduction) * [Variables](#-2-variables) From f565baaf9f977bdaf69cb2b65fb0eed49686c6c6 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 09:36:33 +0530 Subject: [PATCH 37/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 467fdbd..334d43b 100644 --- a/README.md +++ b/README.md @@ -2351,7 +2351,7 @@ console.log("z: " + z); // 6 ```js const { i = 2, j = 4, k = 6 } = { n: 10 }; -console.log("i: " + i); // 10 +console.log("i: " + i); // 2 console.log("j: " + j); // 4 console.log("k: " + k); // 6 ``` From 9140b1ccf4b24d1752ade2fe2fc8bfeebce762c3 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 10:34:12 +0530 Subject: [PATCH 38/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 334d43b..690021d 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ let name = `Abhinav Sharma`; console.log(`Hi, ${name}`); // Output: "Abhinav Sharma" // Multiline String -let msg = `Hello \ +let msg = `Hello \n World`; console.log(`${msg}`); // Output: "Hello World" ``` From a4d9da90771c04da089f5b8e52db6104b687b8fc Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 15:35:39 +0530 Subject: [PATCH 39/82] Update README.md --- README.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 690021d..02925e7 100644 --- a/README.md +++ b/README.md @@ -189,12 +189,23 @@ Fruits: Apple, Orange and Banana **2.5. Spread syntax for object literals:** ```js -var obj1 = { id: 101, name: 'Rajiv Sandal' } -var obj2 = { age: 35, country: 'INDIA' } +const obj1 = { id: 101, name: 'Rajiv Sandal' } +const obj2 = { age: 35, country: 'INDIA' } const employee = { ...obj1, ...obj2 } -console.log(employee); // { "id": 101, "name": "Rajiv Sandal", "age": 35, "country": "INDIA" } +console.log(employee); +``` + +Output: + +```js +{ + "id": 101, + "name": "Rajiv Sandal", + "age": 35, + "country": "INDIA" +} ```
From 410fe78477607a413a486121f4dcba3b1f5a2257 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 15:39:21 +0530 Subject: [PATCH 40/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02925e7..a21c50f 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ Sets are a new object type with ES6 (ES2015) that allow to create collections of ```js let numbers = new Set([10, 20, 20, 30, 40, 50]); -console.log(numbers); // Set(5) {10, 20, 30, 40, 50} +console.log(numbers); Set(5) { 10, 20, 30, 40, 50 } console.log(typeof numbers); // Object ``` From 758fc37c615c70a494e89ba362b6f9f8dabb17c7 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 15:43:43 +0530 Subject: [PATCH 41/82] Update README.md --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a21c50f..c0c4178 100644 --- a/README.md +++ b/README.md @@ -289,15 +289,14 @@ console.log(add(10, 20)); // 30 /** * Using Arrow function */ -let person = { +const person = { name: "Diksha", actions: ["bike", "hike", "ski"], printActions() { this.actions.forEach((action) => { - let str = this.name + " likes to " + action; - console.log(str); + console.log(this.name + " likes to " + action); }); - } + }, }; person.printActions(); From d47f4471ae5422be055583e195150b217ffa6fd1 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 15:47:15 +0530 Subject: [PATCH 42/82] Update README.md --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c0c4178..bdb9318 100644 --- a/README.md +++ b/README.md @@ -417,12 +417,10 @@ var x = 10; if (x === 10) { var x = 20; - console.log(x); - // expected output: 20 + console.log(x); // expected output: 20 } -console.log(x); -// expected output: 20 +console.log(x); // expected output: 20 ``` **Example:** Declaring global variable within function From e46d93a1b7421eed4138a8a6ade2fbb95e1e59c7 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 16:05:33 +0530 Subject: [PATCH 43/82] Update README.md --- README.md | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index bdb9318..957b90c 100644 --- a/README.md +++ b/README.md @@ -603,7 +603,7 @@ Hello Sadhika Sandal **Example 02:** Variable Hoisting ```js -console.log(message); // output : undefined +console.log(message); // output: undefined var message = "The variable Has been hoisted"; ``` @@ -735,12 +735,10 @@ var x = 1; if (x === 1) { var x = 2; - console.log(x); - // expected output: 2 + console.log(x); // expected output: 2 } -console.log(x); -// expected output: 2 +console.log(x); // expected output: 2 ``` ```js @@ -996,19 +994,17 @@ A BigInt number is created by appending `n` to the end of an integer. ```js // BigInt value -const num1 = 900719925124740998n; -const num2 = 900719925124740998n; +const num1 = 100000000000000000n; +const num2 = 1000000000000000000n; const num3 = 10; - // Adding two big integers const result1 = num1 + num2; -console.log(result1); // "1801439850249481996n" - +console.log(result1); // "1100000000000000000n" // Error! BitInt and number cannot be added -const result2 = num1 + num2 + num3; -console.log(result2); // Uncaught TypeError: Cannot mix BigInt and other types +const result2 = num1 + num2 + num3; +console.log(result2); // Uncaught TypeError: Cannot mix BigInt and other types ``` **Boolean:** From 9a3167ba8e039ae9ac63048dfabd1ac5efe4ced7 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 16:54:28 +0530 Subject: [PATCH 44/82] Update README.md --- README.md | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 957b90c..be3c6cf 100644 --- a/README.md +++ b/README.md @@ -1228,12 +1228,16 @@ JavaScript provides a special operator called ternary operator `:?` that assigns ```js ? : ; +``` + +**Example:** -// Example -let a = 10, b = 20; +```js +const a = 10; +const b = 20; -let c = a > b ? a : b; // 20 -let d = a > b ? b : a; // 10 +console.log(a > b ? a : b); // 20 +console.log(a > b ? b : a); // 10 ``` **typeof Operator:** It uses to find type of variable. @@ -1242,11 +1246,20 @@ let d = a > b ? b : a; // 10 ```js typeof variable +``` + +**Example:** -// Example -Let a = 10; +```js +const a = 10; +const obj = {}; +const str = "Hello World"; +const num = [10, 20, 30]; typeof a // number +typeof obj // object +typeof str // string +typeof num // object ```
From 614ffe7d15807eb33c4bdaf405fccdbe1693e702 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 16:59:05 +0530 Subject: [PATCH 45/82] Update README.md --- README.md | 52 +++++++++------------------------------------------- 1 file changed, 9 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index be3c6cf..3ff0406 100644 --- a/README.md +++ b/README.md @@ -1220,48 +1220,6 @@ The assignment operators to assign values to variables with less key strokes. |/= |Divide left operand value by right operand value and assign the result to the left operand.| |%= |Get the modulus of left operand divide by right operand and assign resulted modulus to the left operand.| -**Ternary Operators:** - -JavaScript provides a special operator called ternary operator `:?` that assigns a value to a variable based on some condition. - -**Syntax:** - -```js - ? : ; -``` - -**Example:** - -```js -const a = 10; -const b = 20; - -console.log(a > b ? a : b); // 20 -console.log(a > b ? b : a); // 10 -``` - -**typeof Operator:** It uses to find type of variable. - -**Syntax:** - -```js -typeof variable -``` - -**Example:** - -```js -const a = 10; -const obj = {}; -const str = "Hello World"; -const num = [10, 20, 30]; - -typeof a // number -typeof obj // object -typeof str // string -typeof num // object -``` - @@ -1420,8 +1378,16 @@ console.log(user); // {name: "Sadhika Chaudhuri"} The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement. +**Syntax:** + +```js + ? : ; +``` + +**Example:** + ```js -var isAuthenticated = false; +const isAuthenticated = false; console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated'); ``` From 2402487c488f7be28f9fc2795af2f7904ac9c312 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 8 Dec 2022 17:11:33 +0530 Subject: [PATCH 46/82] Update README.md --- README.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 3ff0406..ee8d964 100644 --- a/README.md +++ b/README.md @@ -1298,37 +1298,37 @@ In JavaScript, the typeof operator returns the data type of its operand in the f **Example:** ```js -typeof undeclaredVariable; // "undefined" +console.log(typeof undeclaredVariable); // "undefined" -var a; -typeof a; // "undefined" +let a; +console.log(typeof a); // "undefined" -a = "Hello World"; -typeof a; // "string" +const b = "Hello World"; +console.log(typeof b); // "string" -a = 42; -typeof a; // "number" +const c = 42; +console.log(typeof c); // "number" -a = 3.1415 -typeof a; // "number" +const d = 3.1415; +console.log(typeof d); // "number" -a = true; -typeof a; // "boolean" +const e = true; +console.log(typeof e); // "boolean" -a = null; -typeof a; // "object" +const f = null; +console.log(typeof f); // "object" -a = undefined; -typeof a; // "undefined" +const g = undefined; +console.log(typeof g); // "undefined" -a = { b: "c" }; -typeof a; // "object" +const h = { b: "c" }; +console.log(typeof h); // "object" -a = function () { +const i = function () { return 10; }; -console.log(typeof a); // "function" +console.log(typeof i); // "function" ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-typeof-jesw53?file=/src/index.js)** From f5e463e4b34ec25debd677e51b486355764ab365 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 16 Dec 2022 13:22:43 +0530 Subject: [PATCH 47/82] Update README.md --- README.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ee8d964..b31261b 100644 --- a/README.md +++ b/README.md @@ -4118,7 +4118,15 @@ try { ↥ back to top
-## # 10.EVENTS +## Q 9.30. How function overloading works in JavaScript? + +*ToDo* + + + +## # 10. EVENTS
@@ -9026,8 +9034,9 @@ Microsoft formerly developed its own proprietary browser engines - Trident and E
#### Q 18.22. What is a Polyfill? -#### Q 18.23. What is optional chaining in javascript? +#### Q 18.23. What is optional chaining in JavaScript? #### Q 18.24. How could you make sure a const value is garbage collected? +#### Q 18.25. How Garbage Collection works in JavaScript? *ToDo* From 2e89030700f0e4a5faa9dadeac57b44006e0caaf Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 26 Jan 2023 15:29:23 +0530 Subject: [PATCH 48/82] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index b31261b..98af22e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ * *[JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics)* * *[JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing)* * *[JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns)* -* *[JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice)* * *[Data Structure in JavaScript](https://github.com/learning-zone/javascript-data-structure)*
From 01b29cfb159d96ae59bfc718a1a66795152bcbd8 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 28 Jan 2023 13:08:04 +0530 Subject: [PATCH 49/82] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 98af22e..c563435 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ * *[CSS Basics](https://github.com/learning-zone/css-basics)* * *[JavaScript ES6 Basics](https://github.com/learning-zone/javascript-es6-basics)* * *[JavaScript Unit Testing](https://github.com/learning-zone/javascript-unit-testing)* +* *[JavaScript Coding Practice](https://github.com/learning-zone/javascript-coding-practice)* * *[JavaScript Design Patterns](https://github.com/learning-zone/javascript-design-patterns)* * *[Data Structure in JavaScript](https://github.com/learning-zone/javascript-data-structure)* From f5da084af1e9adc88a7fa596fb064c6e722c4174 Mon Sep 17 00:00:00 2001 From: kishor82 Date: Sat, 22 Apr 2023 03:19:17 +0530 Subject: [PATCH 50/82] Update README.md Signed-off-by: kishor82 --- README.md | 279 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 272 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c563435..f6e5969 100644 --- a/README.md +++ b/README.md @@ -922,7 +922,28 @@ console.log(y); // 10 ## Q 2.14. What is scope chain in javascript? -*ToDo* +The scope chain in JavaScript refers to the chain of nested scopes that a JavaScript program uses to look up variable and function references. When a variable or function is referenced in JavaScript code, the interpreter first looks for it in the current scope. If it's not found there, it moves up the scope chain to the next outer scope and looks for it there. It continues doing this until the variable or function is found or until it reaches the global scope. + +**Example:**: + +```js +let globalVar = "I'm a global variable"; + +function outer() { + let outerVar = "I'm an outer variable"; + + function inner() { + let innerVar = "I'm an inner variable"; + console.log(innerVar); // "I'm an inner variable" + console.log(outerVar); // "I'm an outer variable" + console.log(globalVar); // "I'm a global variable" + } + + inner(); +} + +outer(); +```
↥ back to top @@ -2637,7 +2658,27 @@ SyntaxError: Rest element must be last element ## Q 7.20. What is difference between [] and new Array()? -*ToDo* +`[]` and `new Array()` are two different ways of creating an array, but they are functionally equivalent. + +The primary difference between them is in how they are created and in their behavior when used with certain methods. + +`[]` is a shorthand for creating a new array. It is the preferred way to create an array in most cases, because it's more concise and easier to read. For example: + +```js +const myArray = []; // create a new empty array +``` + +On the other hand, `new Array()` is a constructor function that creates a new array object. It can be used to create an array of a specific length or with specific elements. For example: + +```js +const myArray = new Array(); // create a new empty array +const myOtherArray = new Array(3); // create a new array with a length of 3 +const myThirdArray = new Array("a", "b", "c"); // create a new array with three elements +``` + +One potential pitfall of using `new Array()` is that it can be ambiguous when you pass a single argument to the constructor. For example, `new Array(3)` creates an array with a length of 3, but `new Array("3")` creates an array with a single element, the string "3". This is because the argument is treated as the value of the first element when it's a non-negative integer, but as the length of the array when it's a string or a negative integer. + +In summary, `[]` is the preferred way to create a new array in JavaScript, while `new Array()` is an alternative way that can be used when you need more control over the array's length or contents.
↥ back to top @@ -4120,7 +4161,27 @@ try { ## Q 9.30. How function overloading works in JavaScript? -*ToDo* +Function overloading refers to the ability to define multiple functions with the same name but with different parameters. In many programming languages, the function to be executed is determined at compile time based on the parameters provided. However, in JavaScript, function overloading does not work in the same way because JavaScript functions can be called with any number and type of arguments. + +One way to achieve function overloading in JavaScript is by using conditional statements to determine the appropriate behavior based on the arguments passed to the function. + +**Example** + +```js +function myFunction() { + if (arguments.length === 1) { + console.log("Hello " + arguments[0]); + } else if (arguments.length === 2) { + console.log("Hello " + arguments[0] + " and " + arguments[1]); + } else { + console.log("Hello world"); + } +} + +myFunction(); // output: "Hello world" +myFunction("Alice"); // output: "Hello Alice" +myFunction("Bob", "Charlie"); // output: "Hello Bob and Charlie" +```
↥ back to top @@ -5857,7 +5918,56 @@ An array is an object so it has all the same capabilities of an object plus a bu ## Q 11.33. What is difference between `{}` vs `new Object()`? -*ToDo* +**1. Object Literal Syntax (`{}`):** + +Object literal syntax is a shorthand way of creating an object. We can create an object by placing a comma-separated list of key-value pairs inside curly braces `{ }`. The key represents a property name of the object and the value represents the value of that property. + +**Syntax:** + +```js +let myObj = { + prop1: value1, + prop2: value2, + prop3: value3 +}; +``` + +**Example:** + +```js +let person = { + name: "John", + age: 30, + city: "New York" +}; +``` + +**2. Object Constructor Syntax (`new Object()`):** + +The object constructor syntax is a way of creating an object using the `new` operator and the `Object` constructor function. We can create an empty object by calling the `Object` constructor without any arguments. We can also create an object by passing an object literal as an argument to the `Object` constructor. + +**Syntax:** + +```js +let myObj = new Object(); +``` + +**Example:** + +```js +let person = new Object(); +person.name = "John"; +person.age = 30; +person.city = "New York"; +``` + +**Difference:** + +The primary difference between using `{}` and `new Object()` to create an object is that the former uses object literal syntax while the latter uses object constructor syntax. + +Object literals are more concise and easier to read and write, especially when creating objects with a small number of properties. On the other hand, object constructors are more flexible and can be used to create objects with properties that are not known at the time of object creation. + +In general, it is recommended to use object literal syntax (`{}`) for creating objects unless there is a specific reason to use the object constructor syntax (`new Object()`).
↥ back to top @@ -7818,7 +7928,35 @@ The `XMLHTTPRequest()` object is an API which is used for fetching data from the ## Q. 15.14. How to get responses of multiple api calls, when some API fails? -*ToDo* +**Promise.allSettled():** + +To handle failures in multiple API calls, `Promise.allSettled()` method can be used. The method returns a Promise that resolves after all of the given promises have either resolved or rejected. It returns an array of objects with two properties: status and value. + +The status property is either "fulfilled" or "rejected", depending on whether the promise was resolved or rejected. The value property is the value of the promise if it was resolved or the reason for rejection if it was rejected. + +**Example:** + +```js +const promises = [fetch('api1'), fetch('api2'), fetch('api3')]; + +Promise.allSettled(promises) + .then(results => { + const successfulResults = []; + const failedResults = []; + + results.forEach(result => { + if (result.status === 'fulfilled') { + successfulResults.push(result.value); + } else { + failedResults.push(result.reason); + } + }); + + console.log('Successful API calls:', successfulResults); + console.log('Failed API calls:', failedResults); + }) + .catch(error => console.log('Error:', error)); +```
↥ back to top @@ -7826,7 +7964,20 @@ The `XMLHTTPRequest()` object is an API which is used for fetching data from the ## Q. 15.15. Explain the use of Promise.any()? -*ToDo* +The `Promise.any()` method is used to handle multiple promises simultaneously, and it resolves with the value of the first fulfilled promise.regardless of whether any of the other promises reject. If all of the promises reject, then `Promise.any()` rejects with an `AggregateError` object that contains an array of rejection reasons. + +The `Promise.any()` method takes an iterable of Promises as an input, and returns a new Promise. Here's an example: + +```javascript +const promise1 = new Promise((resolve, reject) => setTimeout(reject, 1000, 'Promise 1 rejected')); +const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'Promise 2 resolved')); +const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 1500, 'Promise 3 resolved')); + +Promise.any([promise1, promise2, promise3]) + .then((value) => console.log(value)) // 'Promise 2 resolved' + .catch((error) => console.error(error)); // AggregateError: All promises were rejected +``` +*Note: `Promise.any()` is not yet widely supported by all browsers, so you may need to use a polyfill or a different approach to achieve similar functionality in older browsers.*
↥ back to top @@ -9034,11 +9185,125 @@ Microsoft formerly developed its own proprietary browser engines - Trident and E
#### Q 18.22. What is a Polyfill? + +**Polyfill** + +A polyfill is a piece of code (usually a JavaScript library) that provides modern functionality on older browsers that do not support it. It is a way to bring new features to old browsers by mimicking the behavior of modern JavaScript APIs. + +For example, `Object.values()` was introduced in ES2017 and is not supported in some older browsers such as Internet Explorer and Safari 9. However, you can use a polyfill to add support for it in older browsers. + +**Example** + +```js +// polyfill for the Object.values() +if (!Object.values) { + Object.values = function(obj) { + var values = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + values.push(obj[key]); + } + } + return values; + }; +} + +// Now you can use Object.values() even in older browsers that don't support it natively +const obj = { a: 1, b: 2, c: 3 }; +const values = Object.values(obj); + +console.log(values); // Output: [1, 2, 3] +``` + +This code checks if the `Array.prototype.includes()` method is available in the current environment, and if not, it provides an implementation of the method that emulates the behavior of the modern API. This allows you to use the `Array.prototype.includes()` method in older browsers, even though it is not natively supported. + + + + #### Q 18.23. What is optional chaining in JavaScript? + +**Optional chaining** + +Optional chaining is a feature in JavaScript that allows you to safely access nested object properties or functions without worrying about whether the intermediate properties exist or not. It uses the `?.` operator to check for nullish (`null` or `undefined`) values and short-circuits the expression if it encounters one. + +Optional chaining was introduced in ECMAScript 2020 (ES11) and is supported in most modern browsers, but not in older ones. To use it in older browsers, you can use a transpiler like Babel, or write your code with alternative techniques like conditional statements or the `&&` operator. + +**Example** + +```js +const obj = { + a: { + b: { + c: 123 + } + } +}; + +// Without optional chaining +if (obj && obj.a && obj.a.b && obj.a.b.c) { + console.log(obj.a.b.c); // output: 123 +} + +// With optional chaining +console.log(obj?.a?.b?.c); // output: 123 + +// Optional chaining with method +console.log(obj?.a?.b?.c.toString()); // output: "123" +``` + + #### Q 18.24. How could you make sure a const value is garbage collected? + +In JavaScript, garbage collection is automatically performed by the browser or the JavaScript engine. When a value is no longer being used or referenced, it becomes eligible for garbage collection. + +In the case of a const value, the same rules apply as with any other value. As long as the const value is not referenced by any other variables or objects in the program, it will become eligible for garbage collection when the variable goes out of scope. + + +Here are some best practices to follow when working with const variables: + +1. Only use `const` when you know that the value should not be reassigned. + +2. If you ever want to change the contents of the variable for any reason in the future, then don't declare it as const. + +3. Use `let` or `var` instead of `const` if you need to reassign the value. + +4. To ensure that a const value is garbage collected, remove all references to it. + +**Example** + +``` +const myObj = {name: 'John', age: 30}; + +// Use myObj... + +// Remove all references to myObj +myObj = null; +``` + +In this example, setting `myObj` to `null` removes the only reference to the object, allowing it to be garbage collected. + + + #### Q 18.25. How Garbage Collection works in JavaScript? -*ToDo* +JavaScript has an automatic garbage collector that periodically frees up memory that is no longer being used by the program. The garbage collector works by identifying "garbage" values that are no longer accessible or needed by the program and freeing up the memory they occupy. + +**Example** + +```js +let a = { b: { c: { d: "Hello" } } }; +let e = a.b.c; +a = null; +``` +In this code, the object `{ b: { c: { d: "Hello" } } }` is created and assigned to the variable a. The variable e is then assigned a reference to the nested object `{ c: { d: "Hello" } }`. Finally, the variable a is set to null, which means that the original object `{ b: { c: { d: "Hello" } } }` is no longer accessible by the program. + +At this point, the garbage collector will identify the object `{ b: { c: { d: "Hello" } } }` as "garbage" because it is no longer accessible by the program. The garbage collector will then free up the memory occupied by this object.
↥ back to top From 1c283ce0dda3c7b05678202d46fcacbd0e7e876f Mon Sep 17 00:00:00 2001 From: Elias <35622775+EliDeh@users.noreply.github.com> Date: Tue, 23 May 2023 09:47:53 +0200 Subject: [PATCH 51/82] Update README.md fixed comment on first example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6e5969..bc8f776 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Template literals are string literals allowing embedded expressions. ```js // String Substitution let name = `Abhinav Sharma`; -console.log(`Hi, ${name}`); // Output: "Abhinav Sharma" +console.log(`Hi, ${name}`); // Output: "Hi, Abhinav Sharma" // Multiline String let msg = `Hello \n From eb76bf150719bff7bbd5f139977ae9dd2345ea55 Mon Sep 17 00:00:00 2001 From: Nikunj Prajapati Date: Sun, 5 May 2024 19:42:05 +0530 Subject: [PATCH 52/82] Replace unnecessary use of let with const --- README.md | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index bc8f776..5a85e43 100644 --- a/README.md +++ b/README.md @@ -100,8 +100,8 @@ console.log(sum(...numbers)); // 60 **2.1. Copying an array:** ```js -let fruits = ["Apple", "Orange", "Banana"]; -let newFruitArray = [...fruits]; +const fruits = ["Apple", "Orange", "Banana"]; +const newFruitArray = [...fruits]; console.log(newFruitArray); ``` @@ -121,10 +121,10 @@ Output: **2.2. Concatenating arrays:** ```js -let arr1 = ["A", "B", "C"]; -let arr2 = ["X", "Y", "Z"]; +const arr1 = ["A", "B", "C"]; +const arr2 = ["X", "Y", "Z"]; -let result = [...arr1, ...arr2]; +const result = [...arr1, ...arr2]; console.log(result); ``` @@ -144,8 +144,8 @@ Output: **2.3. Spreading elements together with an individual element:** ```js -let fruits = ["Apple", "Orange", "Banana"]; -let newFruits = ["Cherry", ...fruits]; +const fruits = ["Apple", "Orange", "Banana"]; +const newFruits = ["Cherry", ...fruits]; console.log(newFruits); ``` @@ -165,7 +165,7 @@ Output: **2.4. Spreading elements on function calls:** ```js -let fruits = ["Apple", "Orange", "Banana"]; +const fruits = ["Apple", "Orange", "Banana"]; const getFruits = (f1, f2, f3) => { console.log(`Fruits: ${f1}, ${f2} and ${f3}`); @@ -217,7 +217,7 @@ Output: Sets are a new object type with ES6 (ES2015) that allow to create collections of unique values. The values in a set can be either simple primitives like strings or integers, but more complex object types like object literals or arrays can also be part of a set. ```js -let numbers = new Set([10, 20, 20, 30, 40, 50]); +const numbers = new Set([10, 20, 20, 30, 40, 50]); console.log(numbers); Set(5) { 10, 20, 30, 40, 50 } console.log(typeof numbers); // Object @@ -236,7 +236,10 @@ function add(x = 10, y = 20) { console.log(x + y); } -add(10, 30); // 40 +add(10, 30); // Output: 10 + 30 = 40 +add(15); // Output: 15 + 20 = 35 +add(); // Output: 20 + 10 = 30 + ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-default-parametrs-tjw9uk?file=/src/index.js)** @@ -272,7 +275,7 @@ Hello World **6. Arrow Function (=>):** ```js -let add = (x, y) => x + y; +const add = (x, y) => x + y; console.log(add(10, 20)); // 30 ``` @@ -347,7 +350,7 @@ function* generator(num) { yield num + 20; yield num + 30; } -let gen = generator(10); +const gen = generator(10); console.log(gen.next().value); // 20 console.log(gen.next().value); // 30 From 7a26761a49a36eb8c5ab2c72f981f54c91ff570f Mon Sep 17 00:00:00 2001 From: Nikunj Prajapati Date: Mon, 6 May 2024 10:34:13 +0530 Subject: [PATCH 53/82] small fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a85e43..af0dac3 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ function add(x = 10, y = 20) { add(10, 30); // Output: 10 + 30 = 40 add(15); // Output: 15 + 20 = 35 -add(); // Output: 20 + 10 = 30 +add(); // Output: 10 + 20 = 30 ``` From 60052c900d03ff84842df9ba046b71d56a307534 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 12 Apr 2026 12:57:27 +0530 Subject: [PATCH 54/82] Update README.md --- README.md | 873 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 614 insertions(+), 259 deletions(-) diff --git a/README.md b/README.md index af0dac3..9030482 100644 --- a/README.md +++ b/README.md @@ -702,18 +702,13 @@ let aLet = 2; The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. `0`, `null`, `undefined`, etc.), it will be `false`, otherwise, `true`. -For example, you can test IE version using this expression as below, - ```js -let isIE11 = false; -isIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./); -console.log(isIE11); // returns true or false -``` - -If you do not use this expression then it returns the original value. - -```js -console.log(navigator.userAgent.match(/Trident.*rv[ :]*11\./)); // returns either an Array or null +console.log(!!null); // false +console.log(!!undefined); // false +console.log(!!0); // false +console.log(!!""); // false +console.log(!!1); // true +console.log(!!"text"); // true ``` *Note: The expression !! is not an operator, but it is just twice of ! operator*. @@ -876,36 +871,6 @@ Hoist(20); // 20 ↥ back to top
-## Q 2.12. Explain `var self = this` in JavaScript? - -The **self** is being used to maintain a reference to the original this even as the context is changing. It is a technique often used in event handlers ( especially in closures ). - -`this` is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping ( in C open/close {} curly braces refers to a block ). JavaScript has two scopes namely, global and local scope. - -**Example:** - -```js -/** - * this Context - */ -const context = { - prop: 10, - getCurrentContext: function () { - return this.prop; - } -}; - -console.log(context.getCurrentContext()); // 10 -``` - -*Note: 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.* - -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-self-this-k1w0e8?file=/src/index.js)** - - - ## Q 2.13. How do you swap variables using destructuring assignment? ```js @@ -1454,7 +1419,7 @@ function getValue(someParam) { ## Q 4.9. What is the difference between `typeof` and `instanceof` operator? -The `typeof` operator checks if a value has type of primitive type which can be one of boolean, function, object, number, string, undefined and symbol (ES6). +The `typeof` operator checks if a value has type of primitive type which can be one of `boolean`, `function`, `object`, `number`, `string`, `undefined`, `symbol`, or `bigint`. **Example:** @@ -1496,6 +1461,88 @@ b instanceof String; // returns true ↥ back to top
+## Q 4.11. What is the nullish coalescing operator (`??`) in JavaScript? + +The **nullish coalescing operator** (`??`) returns the right-hand side operand when the left-hand side operand is `null` or `undefined`. Otherwise, it returns the left-hand side operand. Unlike `||`, it does **not** treat `0`, `false`, or `""` as falsy. + +**Syntax:** + +```js +leftExpr ?? rightExpr +``` + +**Example:** + +```js +console.log(null ?? 'default'); // 'default' +console.log(undefined ?? 'default'); // 'default' +console.log(0 ?? 'default'); // 0 (0 is NOT null/undefined) +console.log('' ?? 'default'); // '' (empty string is NOT null/undefined) +console.log(false ?? 'default'); // false + +// Practical use: provide a fallback for a missing config value +const config = { timeout: 0 }; +const timeout = config.timeout ?? 3000; +console.log(timeout); // 0 (not 3000, because 0 is a valid value) +``` + +**Nullish coalescing assignment (`??=`):** + +```js +let user = { name: null }; +user.name ??= 'Anonymous'; +console.log(user.name); // 'Anonymous' +``` + + + +## Q 4.12. What are logical assignment operators in JavaScript? + +Logical assignment operators (ES2021) combine a logical operator with assignment. There are three: + +| Operator | Equivalent to | Description | +|----------|-----------------------|-------------| +| `&&=` | `a && (a = b)` | Assigns `b` to `a` only if `a` is **truthy** | +| `\|\|=` | `a \|\| (a = b)` | Assigns `b` to `a` only if `a` is **falsy** | +| `??=` | `a ?? (a = b)` | Assigns `b` to `a` only if `a` is **null or undefined** | + +**Example:** + +```js +// &&= (AND assignment) +let a = 1; +a &&= 2; +console.log(a); // 2 (a was truthy, so assigned) + +let b = 0; +b &&= 2; +console.log(b); // 0 (b was falsy, not assigned) + +// ||= (OR assignment) +let c = null; +c ||= 'default'; +console.log(c); // 'default' (c was falsy) + +let d = 'existing'; +d ||= 'default'; +console.log(d); // 'existing' (d was truthy, not reassigned) + +// ??= (Nullish assignment) +let e = null; +e ??= 'fallback'; +console.log(e); // 'fallback' + +let f = 0; +f ??= 'fallback'; +console.log(f); // 0 (0 is not null/undefined) +``` + + + ## # 5. NUMBERS
@@ -1786,7 +1833,7 @@ Warning: *Executing JavaScript from a string is an enormous security risk. It is ## Q 6.5. How do you check if a string starts with another string? -You can use ECMAScript 6 `String.prototype.startsWith()` method to check a string starts with another string or not. But it is not yet supported in all browsers. Let us see an example to see this usage, +You can use `String.prototype.startsWith()` method to check if a string starts with another string or not. It is fully supported in all modern browsers. ```js let str = "Hello World"; @@ -1801,6 +1848,42 @@ console.log(str.startsWith("World")); // false ↥ back to top
+## Q 6.6. What are `replaceAll()`, `padStart()` and `padEnd()` string methods? + +**1. String.prototype.replaceAll():** + +The `replaceAll()` method returns a new string with all matches of a pattern replaced by a replacement. Unlike `replace()`, it replaces every occurrence without needing a global regex flag. + +```js +const text = 'I like cats. Cats are cute cats.'; +console.log(text.replace('cats', 'dogs')); // 'I like dogs. Cats are cute cats.' (only first) +console.log(text.replaceAll('cats', 'dogs')); // 'I like dogs. Cats are cute dogs.' +``` + +**2. String.prototype.padStart():** + +The `padStart()` method pads the current string with another string from the **start** until it reaches the given length. + +```js +console.log('5'.padStart(3, '0')); // '005' +console.log('hello'.padStart(8)); // ' hello' (default pad is space) +console.log('42'.padStart(5, '*')); // '***42' +``` + +**3. String.prototype.padEnd():** + +The `padEnd()` method pads the current string with another string from the **end** until it reaches the given length. + +```js +console.log('5'.padEnd(3, '0')); // '500' +console.log('hello'.padEnd(8)); // 'hello ' +console.log('42'.padEnd(5, '-')); // '42---' +``` + + + ## # 7. ARRAY
@@ -2216,6 +2299,55 @@ var pets = ['cat', 'dog', 'bat']; console.log(pets.includes('at')); // Output: false ``` +**18. array.at()**: + +The `at()` method (ES2022) takes an integer and returns the item at that index. Negative integers count back from the last item. + +```js +const fruits = ['Apple', 'Orange', 'Banana', 'Mango']; +console.log(fruits.at(0)); // Output: Apple +console.log(fruits.at(-1)); // Output: Mango (last element) +console.log(fruits.at(-2)); // Output: Banana +``` + +**19. array.flat()**: + +The `flat()` method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. + +```js +const nested = [1, [2, 3], [4, [5, 6]]]; +console.log(nested.flat()); // Output: [1, 2, 3, 4, [5, 6]] +console.log(nested.flat(2)); // Output: [1, 2, 3, 4, 5, 6] +console.log(nested.flat(Infinity)); // Output: [1, 2, 3, 4, 5, 6] +``` + +**20. array.flatMap()**: + +The `flatMap()` method maps each element using a mapping function, then flattens the result into a new array (one level deep). + +```js +const sentences = ['Hello World', 'Foo Bar']; +console.log(sentences.flatMap(s => s.split(' '))); // Output: ['Hello', 'World', 'Foo', 'Bar'] +``` + +**21. array.findLast()**: + +The `findLast()` method (ES2023) iterates the array in reverse and returns the value of the first element that satisfies the provided testing function. + +```js +const numbers = [5, 12, 8, 130, 44]; +console.log(numbers.findLast(n => n > 10)); // Output: 44 +``` + +**22. array.findLastIndex()**: + +The `findLastIndex()` method (ES2023) iterates the array in reverse and returns the index of the first element that satisfies the provided testing function. + +```js +const numbers = [5, 12, 8, 130, 44]; +console.log(numbers.findLastIndex(n => n > 10)); // Output: 4 +``` + @@ -2687,6 +2819,53 @@ In summary, `[]` is the preferred way to create a new array in JavaScript, while ↥ back to top
+## Q 7.21. What are `Array.from()`, `Array.of()` and `Array.isArray()` methods? + +**1. Array.from():** + +`Array.from()` creates a new, shallow-copied array from an array-like or iterable object such as a `Set`, `Map`, `NodeList`, or string. + +```js +// From a string +console.log(Array.from('hello')); // ['h', 'e', 'l', 'l', 'o'] + +// From a Set +const set = new Set([1, 2, 3, 2, 1]); +console.log(Array.from(set)); // [1, 2, 3] + +// With a map function +console.log(Array.from([1, 2, 3], x => x * 2)); // [2, 4, 6] + +// From array-like object +console.log(Array.from({ length: 3 }, (_, i) => i + 1)); // [1, 2, 3] +``` + +**2. Array.of():** + +`Array.of()` creates a new array from a variable number of arguments, regardless of number or type. It fixes the ambiguity of `new Array()` with a single numeric argument. + +```js +console.log(Array.of(7)); // [7] (one element) +console.log(new Array(7)); // [ , , , , , , ] (empty array of length 7!) + +console.log(Array.of(1, 2, 3)); // [1, 2, 3] +``` + +**3. Array.isArray():** + +`Array.isArray()` returns `true` if the passed value is an array, `false` otherwise. It is more reliable than `instanceof` when working across different frames or windows. + +```js +console.log(Array.isArray([1, 2, 3])); // true +console.log(Array.isArray('hello')); // false +console.log(Array.isArray({ length: 3 })); // false +console.log(Array.isArray(new Array())); // true +``` + + + ## # 8. Regular Expression
@@ -4190,6 +4369,62 @@ myFunction("Bob", "Charlie"); // output: "Hello Bob and Charlie" ↥ back to top
+## Q 9.31. What is an IIFE (Immediately Invoked Function Expression)? + +An **IIFE** (Immediately Invoked Function Expression) is a JavaScript function that is defined and executed immediately after its creation. It creates a private scope so that variables inside it do not pollute the global scope. + +**Syntax:** + +```js +(function () { + // code here +})(); + +// Arrow function variant +(() => { + // code here +})(); +``` + +**Example:** + +```js +const result = (function () { + const message = 'Hello from IIFE'; + return message; +})(); + +console.log(result); // 'Hello from IIFE' +console.log(typeof message); // 'undefined' — private to the IIFE +``` + +**Use cases:** + +* **Avoid global namespace pollution** — keeps variables local +* **Module pattern** — expose only what's needed through the return value +* **Initialization code** — logic that runs once and doesn't need to be callable later + +```js +// Counter using IIFE +const counter = (function () { + let count = 0; + return { + increment() { return ++count; }, + decrement() { return --count; }, + value() { return count; } + }; +})(); + +console.log(counter.increment()); // 1 +console.log(counter.increment()); // 2 +console.log(counter.decrement()); // 1 +console.log(counter.value()); // 1 +``` + + + ## # 10. EVENTS
@@ -5493,11 +5728,31 @@ console.log(newObj); // { a: 10, b: { c: 20 } } ## Q 11.18. Write a function called deepClone which takes an object and creates a object copy of it? -``` javascript -var newObject = deepClone(obj); +**Modern approach — using `structuredClone()` (ES2022):** + +`structuredClone()` is a built-in global function that performs a deep clone of any serializable value. It supports objects, arrays, `Date`, `RegExp`, `Map`, `Set`, and more. + +```js +const personalDetail = { + name: 'Alex', + address: { + location: 'xyz', + zip: '123456', + phoneNumber: { + homePhone: 8797912345, + workPhone: 1234509876 + } + } +}; + +const newObject = structuredClone(personalDetail); +newObject.address.zip = '999999'; + +console.log(personalDetail.address.zip); // '123456' (original unchanged) +console.log(newObject.address.zip); // '999999' ``` -Solution: +**Manual recursive approach (for environments without `structuredClone`):** ```js function deepClone(object) { @@ -5513,24 +5768,6 @@ function deepClone(object) { } ``` -**Explanation:** We have been asked to do deep copy of object so What is basically It is mean ?. Let us understand in this way you have been given an object `personalDetail` this object contains some property which again a type of object here as you can see `address` is an object and `phoneNumber` in side an `address` is also an object. In simple term `personalDetail` is nested object(object inside object). So Here deep copy means we have to copy all the property of `personalDetail` object including nested object. - -```js -var personalDetail = { - name : 'Alex', - address : { - location: 'xyz', - zip : '123456', - phoneNumber : { - homePhone: 8797912345, - workPhone : 1234509876 - } - } -} -``` - -So when we do deep clone then we should copy every property (including the nested object). - @@ -5590,6 +5827,17 @@ const obj = { key: undefined }; console.log(obj.hasOwnProperty("key")); // true ``` +**3. Using `Object.hasOwn()` (ES2022 — preferred):** + +`Object.hasOwn()` is the modern replacement for `hasOwnProperty()`. It is safer because it works correctly even on objects created with `Object.create(null)` (which have no prototype). + +```js +const obj = { key: undefined }; + +console.log(Object.hasOwn(obj, "key")); // true +console.log(Object.hasOwn(obj, "missing")); // false +``` + **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-in-operator-3fxd3h?file=/src/index.js)**
@@ -5598,17 +5846,17 @@ console.log(obj.hasOwnProperty("key")); // true ## Q 11.21. How do you loop through or enumerate javascript object? -You can use the `for-in` loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn\'t come from the prototype using `hasOwnProperty` method. +You can use the `for-in` loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn\'t come from the prototype using `Object.hasOwn()` (ES2022) or the older `hasOwnProperty()` method. ```js -var object = { +const object = { "k1": "value1", "k2": "value2", "k3": "value3" }; -for (var key in object) { - if (object.hasOwnProperty(key)) { +for (const key in object) { + if (Object.hasOwn(object, key)) { console.log(key + " -> " + object[key]); // k1 -> value1 ... } } @@ -5620,13 +5868,13 @@ for (var key in object) { ## Q 11.22. How do you test for an empty object? -**a.) Using Object keys(ECMA 5+):** You can use object keys length along with constructor type. +**a. Using Object keys(ECMA 5+):** You can use object keys length along with constructor type. ```js Object.keys(obj).length === 0 && obj.constructor === Object ``` -**b.) Using Object entries(ECMA 7+):** You can use object entries length along with constructor type. +**b. Using Object entries(ECMA 7+):** You can use object entries length along with constructor type. ```js Object.entries(obj).length === 0 && obj.constructor === Object @@ -5976,6 +6224,48 @@ In general, it is recommended to use object literal syntax (`{}`) for creating o ↥ back to top
+## Q 11.34. What is the `Object.fromEntries()` method? + +`Object.fromEntries()` transforms a list of key-value pairs (such as an array of `[key, value]` pairs or a `Map`) into a plain object. It is the inverse of `Object.entries()`. + +**Syntax:** + +```js +Object.fromEntries(iterable) +``` + +**Example 1: From an array of entries** + +```js +const entries = [['name', 'Alice'], ['age', 30], ['city', 'Paris']]; +const obj = Object.fromEntries(entries); +console.log(obj); // { name: 'Alice', age: 30, city: 'Paris' } +``` + +**Example 2: From a Map** + +```js +const map = new Map([['a', 1], ['b', 2], ['c', 3]]); +const obj = Object.fromEntries(map); +console.log(obj); // { a: 1, b: 2, c: 3 } +``` + +**Example 3: Transforming an object (entries → transform → fromEntries)** + +```js +const prices = { apple: 1.5, banana: 0.75, cherry: 3.0 }; + +// Double all prices +const doubled = Object.fromEntries( + Object.entries(prices).map(([key, val]) => [key, val * 2]) +); +console.log(doubled); // { apple: 3, banana: 1.5, cherry: 6 } +``` + + + # # 12. WINDOW AND DOCUMENT OBJECT
@@ -6540,22 +6830,6 @@ window.history.pushState('newPage', 'Title', '/newPage.html'); ↥ back to top
-## Q 12.17. When would you use `document.write()`? - -The **document.write()** method is used to delete all the content from the HTML document and inserts the new content. It is also used to give the additional text to an output which is open by the `document.open()` method. - -The `document.write()` only works while the page is loading; If you call it after the page is done loading, it will overwrite the whole page. This method is mostly used for testing purpose. - -**Example:** - -```js -document.write("Hello World!"); -``` - - - ## Q 12.18. What is the difference between an attribute and a property? Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value, @@ -6783,35 +7057,6 @@ if (typeof(Storage) !== "undefined") { ↥ back to top -## Q 12.25. How to detect browser type in javascript? - -To detect user browser information use the `navigator.userAgent()` property. - -```js -let browser; -const agt = navigator.userAgent.toLowerCase(); - -if (agt.indexOf("chrome") > -1) { - browser = "Google Chrome"; -} else if (agt.indexOf("safari") > -1) { - browser = "Apple Safari"; -} else if (agt.indexOf("opera") > -1) { - browser = "Opera"; -} else if (agt.indexOf("firefox") > -1) { - browser = "Mozilla Firefox"; -} else if (agt.indexOf("mise") > -1 || agt.indexOf("trident") > -1) { - browser = "Microsoft Internet Explorer"; -} - -alert("You are using: " + browser + " \n\nNavigator: " + agt); -``` - -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-detect-browser-type-7xufzy?file=/src/index.js)** - - - # # 13. CLASSES
@@ -7337,6 +7582,77 @@ console.log(User.isAdmin); // false ↥ back to top +## Q 13.16. What are private class fields in JavaScript? + +Private class fields (ES2022) use the `#` prefix to declare fields that are only accessible from inside the class body. They are a true hard private — not accessible via `obj['#field']` or any workaround. + +**Syntax:** + +```js +class ClassName { + #privateField = defaultValue; + #privateMethod() { ... } +} +``` + +**Example:** + +```js +class BankAccount { + #balance; + #owner; + + constructor(owner, initialBalance) { + this.#owner = owner; + this.#balance = initialBalance; + } + + deposit(amount) { + if (amount > 0) this.#balance += amount; + } + + withdraw(amount) { + if (amount <= this.#balance) this.#balance -= amount; + else throw new Error('Insufficient funds'); + } + + get info() { + return `${this.#owner}: \$${this.#balance}`; + } +} + +const acc = new BankAccount('Alice', 1000); +acc.deposit(500); +console.log(acc.info); // 'Alice: $1500' + +// Private fields are inaccessible outside the class: +console.log(acc.#balance); // SyntaxError +``` + +**Private static fields and methods** are also supported: + +```js +class Counter { + static #count = 0; + + constructor() { + Counter.#count++; + } + + static getCount() { + return Counter.#count; + } +} + +new Counter(); +new Counter(); +console.log(Counter.getCount()); // 2 +``` + + + ## # 14. ERROR HANDLING
@@ -7471,6 +7787,55 @@ errorHandling(); // Error: is not a number. ↥ back to top +## Q 14.4. How do you create a custom error class in JavaScript? + +You can create a custom error class by extending the built-in `Error` class. This lets you define domain-specific errors with custom names and additional properties. + +**Example:** + +```js +class ValidationError extends Error { + constructor(message, field) { + super(message); + this.name = 'ValidationError'; + this.field = field; + } +} + +class NetworkError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'NetworkError'; + this.statusCode = statusCode; + } +} + +// Usage +function validateAge(age) { + if (typeof age !== 'number') { + throw new ValidationError('Age must be a number', 'age'); + } + if (age < 0 || age > 150) { + throw new ValidationError('Age must be between 0 and 150', 'age'); + } +} + +try { + validateAge('twenty'); +} catch (err) { + if (err instanceof ValidationError) { + console.log(`Validation failed on field "${err.field}": ${err.message}`); + // Validation failed on field "age": Age must be a number + } else { + throw err; // rethrow unexpected errors + } +} +``` + + + ## # 15. PROMISES
@@ -7611,12 +7976,12 @@ Below are the list of pros and cons of promises over callbacks, * Easy to write parallel asynchronous code with `Promise.all()` * Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions) * Integrated error handling. +* Additional static methods: `Promise.allSettled()`, `Promise.any()`, `Promise.race()` **Cons:** * It makes little complex code * It cannot return multiple arguments. -* We need to load a polyfill if ES6 is not supported
↥ back to top @@ -7849,82 +8214,6 @@ const myRequest = new Request('flowers.jpg', myInit); myContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg' ``` - - -## Q 15.12. Explain ajax request in javascript? - -Ajax stands for Asynchronous Javascript And Xml. It load data from the server and selectively updating parts of a web page without reloading the whole page. - -Basically, Ajax uses browser\'s built-in `XMLHttpRequest()` object to send and receive information to and from a web server asynchronously, in the background, without blocking the page or interfering with the user\'s experience. - -

- Ajax -

- -**Example:** - -```js -(function() { - var xhr; - document.getElementById('ajaxButton').addEventListener('click', makeRequest); - - function makeRequest() { - if (window.XMLHttpRequest) { - // code for IE7+, Firefox, Chrome, Opera, Safari - xhr = new XMLHttpRequest(); - } else { - // code for IE6, IE5 - xhr = new ActiveXObject('Microsoft.XMLHTTP'); - } - xhr.onreadystatechange = function() { - if (this.readyState == 4 && this.status == 200) { - document.getElementById("result").innerHTML = '
' + this.responseText + '
'; - } - }; - xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); //this makes asynchronous true or false - xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - xhr.send(); - } - })(); -``` - -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-ajax-ntgmov?file=/src/index.js)** - - - -## Q 15.13. What is XMLHTTPRequest Object? - -The `XMLHTTPRequest()` object is an API which is used for fetching data from the server. An object of XMLHTTPRequest is used for asynchronous communication between client and server. It retrieve any type of data such as json, xml, text etc. - -**XMLHttpRequest Object Methods:** - -|Method |Description | -|-----------------------|-----------------------------------| -|new XMLHttpRequest() |Creates a new XMLHttpRequest object| -|abort() |Cancels the current request| -|getAllResponseHeaders()|Returns header information| -|getResponseHeader() |Returns specific header information| -|open(method,url,async,user,psw)| Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password| -|send() |Sends the request to the server
Used for GET requests| -|send(string) |Sends the request to the server.
Used for POST requests| -|setRequestHeader() |Adds a label/value pair to the header to be sent| - -**XMLHttpRequest Object Properties:** - -|Property |Description | -|--------------------|-------------------------------------| -|onreadystatechange |Defines a function to be called when the readyState property changes -|readyState |Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready| -|responseText |Returns the response data as a string -|responseXML |Returns the response data as XML data -|status |Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"| -|statusText |Returns the status-text (e.g. "OK" or "Not Found")| - - @@ -7980,7 +8269,7 @@ Promise.any([promise1, promise2, promise3]) .then((value) => console.log(value)) // 'Promise 2 resolved' .catch((error) => console.error(error)); // AggregateError: All promises were rejected ``` -*Note: `Promise.any()` is not yet widely supported by all browsers, so you may need to use a polyfill or a different approach to achieve similar functionality in older browsers.* +*Note: `Promise.any()` is supported in all modern browsers since 2021.*
↥ back to top @@ -8044,10 +8333,6 @@ console.log(map); 2. WeakMap objects doesn\'t avert garbage collection if there are no references to the object which is acting like a key. Therefore there is no method to retrieve keys in WeakMap, whereas in Map there are methods such as `Map.prototype.keys()` to get the keys. 3. There is no size property exists in WeakMap. -**Browser support for Map and WeakMap:** - -The latest Chrome, Firefox, Edge and Safari support Map and WeakMap on desktop. It\'s supported only in IE11 but not IE10 and below. On mobile, newer browsers also have support, but IE Mobile doesn\'t. - **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-request-object-ro4xt9?file=/src/index.js)**
@@ -8287,6 +8572,57 @@ export class Alligator { ↥ back to top
+## Q 17.2. What is dynamic import in JavaScript? + +Dynamic `import()` (ES2020) allows you to import a module **on demand** at runtime rather than statically at the top of a file. It returns a **Promise** that resolves to the module object, enabling lazy loading and code splitting. + +**Syntax:** + +```js +import(moduleSpecifier).then(module => { ... }); + +// or with async/await +const module = await import(moduleSpecifier); +``` + +**Example: Lazy-loading a module** + +```js +// math.js +export function add(a, b) { return a + b; } +export function multiply(a, b) { return a * b; } +``` + +```js +// main.js — only loads math.js when the button is clicked +document.getElementById('btn').addEventListener('click', async () => { + const math = await import('./math.js'); + console.log(math.add(2, 3)); // 5 + console.log(math.multiply(4, 5)); // 20 +}); +``` + +**Example: Conditional import** + +```js +const lang = navigator.language.startsWith('fr') ? 'fr' : 'en'; +const messages = await import(`./locales/${lang}.js`); +console.log(messages.default.greeting); +``` + +**Key differences from static imports:** + +| Feature | Static `import` | Dynamic `import()` | +|-----------------|-----------------|---------------------| +| Location | Top of file only | Anywhere in code | +| Timing | Compile time | Runtime | +| Returns | Binding | Promise | +| Tree-shaking | Yes | Limited | + + + ## # 18. MISCELLANEOUS
@@ -8355,42 +8691,6 @@ You can use `
-## Q 18.3. What is the difference between feature detection, feature inference, and using the UA string? - -**1. Feature Detection** - -Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn\'t), so that the browser can always provide a working experience rather crashing/erroring in some browsers. For example: - -```js -if ('geolocation' in navigator) { - // Can use navigator.geolocation -} else { - // Handle lack of feature -} -``` - -[Modernizr](https://modernizr.com/) is a great library to handle feature detection. - -**2. Feature Inference** - -Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.: - -```js -if (document.getElementsByTagName) { - element = document.getElementById(id); -} -``` - -This is not really recommended. Feature detection is more foolproof. - -**3. UA String** - -This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via `navigator.userAgent`. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method. - - - ## Q 18.4. What is strict mode? The Strict Mode is allows you to place a program, or a function, in a `strict` operating context. This strict context prevents certain actions from being taken and throws more exceptions. @@ -8471,32 +8771,6 @@ console.log(obj2 === obj1); // true ↥ back to top
-## Q 18.6. What do you understand by ViewState and SessionState? - -**1. Session State**: - -Contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It is a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state. - -* Maintained at session level. -* Session state value availability is in all pages available in a user session. -* Information in session state stored in the server. -* In session state, user data remains in the server. The availability of the data is guaranteed until either the user closes the session or the browser is closed. -* Session state is used for the persistence of user-specific data on the server\'s end. - -**2. View State**: - -On the other hand is information specific to particular web page. It is stored in a hidden field so that it is not visible to the user. - -* Maintained at page level only. -* View state can only be visible from a single page and not multiple pages. -* Information stored on the client\'s end only. -* View state will retain values in the event of a postback operation occurring. -* View state is used to allow the persistence of page-instance-specific data. - - - ## Q 18.7. Explain browser console logs features? The `Console` method **log()** outputs a message to the web console. The message may be a single string or it may be any one or more JavaScript objects. @@ -9311,3 +9585,84 @@ At this point, the garbage collector will identify the object `{ b: { c: { d: "H + +#### Q 18.26. What is the JavaScript Event Loop? + +The **Event Loop** is the mechanism that allows JavaScript — a single-threaded language — to perform non-blocking asynchronous operations. It continuously monitors the **call stack** and the **task queues** and moves tasks from the queues to the stack when the stack is empty. + +**Components:** + +* **Call Stack** — executes synchronous code one frame at a time (LIFO). +* **Web APIs** (or Node.js APIs) — handle async operations like `setTimeout`, `fetch`, DOM events. +* **Macrotask queue** (Task Queue) — holds callbacks from `setTimeout`, `setInterval`, I/O, UI events. +* **Microtask queue** — holds Promise callbacks (`.then`, `.catch`, `.finally`) and `queueMicrotask()`. + +**Execution order:** + +1. Execute all synchronous code on the call stack. +2. Drain the **entire** microtask queue (including any microtasks added during this step). +3. Pick **one** macrotask from the macrotask queue. +4. Repeat from step 2. + +**Example:** + +```js +console.log('1 - sync'); + +setTimeout(() => console.log('2 - setTimeout (macrotask)'), 0); + +Promise.resolve() + .then(() => console.log('3 - Promise.then (microtask)')) + .then(() => console.log('4 - Promise.then (microtask)')); + +console.log('5 - sync'); + +// Output: +// 1 - sync +// 5 - sync +// 3 - Promise.then (microtask) +// 4 - Promise.then (microtask) +// 2 - setTimeout (macrotask) +``` + + + +#### Q 18.27. What is the difference between microtask queue and macrotask queue? + +| Feature | Microtask Queue | Macrotask Queue | +|------------------|------------------------------------------|----------------------------------------| +| Also called | Job queue | Task queue / callback queue | +| Sources | `Promise.then/catch/finally`, `queueMicrotask()`, `MutationObserver` | `setTimeout`, `setInterval`, `setImmediate` (Node), I/O, UI events | +| Priority | **Higher** — runs before next macrotask | Lower — runs one at a time | +| When processed | After every task, until queue is empty | One per event loop iteration | + +**Example showing microtasks before macrotasks:** + +```js +setTimeout(() => console.log('macrotask 1'), 0); +setTimeout(() => console.log('macrotask 2'), 0); + +Promise.resolve() + .then(() => { + console.log('microtask 1'); + return Promise.resolve(); + }) + .then(() => console.log('microtask 2')); + +queueMicrotask(() => console.log('microtask 3')); + +// Output: +// microtask 1 +// microtask 3 +// microtask 2 +// macrotask 1 +// macrotask 2 +``` + +*Note: All microtasks are fully drained before the event loop picks the next macrotask.* + + From b250c57681f914bed8ea42894b21b3f8dcf3f980 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 29 Apr 2026 12:48:29 +0530 Subject: [PATCH 55/82] Update README.md --- README.md | 2799 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 2497 insertions(+), 302 deletions(-) diff --git a/README.md b/README.md index 9030482..f324329 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ * [Collections](#-16-collections) * [Modules](#-17-modules) * [Miscellaneous](#-18-miscellaneous) +* [Tooling & Build Process](#-19-tooling--build-process) +* [Progressive Web Apps](#-20-progressive-web-apps-pwa)
@@ -43,7 +45,7 @@
-## Q 1.1. List out important features of JavaScript ES6? +## Q. List out important features of JavaScript ES6? **1. Template Strings:** @@ -406,7 +408,7 @@ console.log(iterateIt.next().value); //output: 6
-## Q 2.1. What are global variables? +## Q. What are global variables? Global variables are declared outside of a function or declared with a window object for accessibility throughout the program (unless shadowed by locals). If you declare a variable without using var, even if it\'s inside a function, it will still be seen as global. @@ -457,7 +459,7 @@ console.log(getValue()); // 100 ↥ back to top -## Q 2.2. What are template literals in es6? +## Q. What are template literals in es6? Template literals help make it simple to do string interpolation, or to include variables in a string. @@ -494,7 +496,7 @@ document.body.innerHTML = ` ↥ back to top -## Q 2.3. What are the differences between variables created using `let`, `var` or `const`? +## Q. What are the differences between variables created using `let`, `var` or `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). @@ -541,10 +543,10 @@ console.log(c); // ReferenceError: c is not defined console.log(a); // undefined var a = 'foo'; -console.log(b); // ReferenceError: can't access lexical declaration 'b' before initialization +console.log(b); // ReferenceError: can\'t access lexical declaration 'b' before initialization let b = 'baz'; -console.log(c); // ReferenceError: can't access lexical declaration 'c' before initialization +console.log(c); // ReferenceError: can\'t access lexical declaration 'c' before initialization const c = 'bar'; ``` @@ -559,7 +561,7 @@ let b = 'baz'; let b = 'qux'; // Uncaught SyntaxError: Identifier 'b' has already been declared ``` -`let` and `const` differ in that `let` allows reassigning the variable's value while `const` does not. +`let` and `const` differ in that `let` allows reassigning the variable\'s value while `const` does not. ```js // This is ok. @@ -579,7 +581,7 @@ console.log(b) // TypeError: Assignment to constant variable. ↥ back to top -## Q 2.4. What is Hoisting in JavaScript? +## Q. What is Hoisting in JavaScript? JavaScript **Hoisting** refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. @@ -639,7 +641,7 @@ They will only get initialized when their lexical binding (assignment) is evalua ↥ back to top -## Q 2.5. In which case the function definition is not hoisted in JavaScript? +## Q. In which case the function definition is not hoisted in JavaScript? Let us take the following **function expression** @@ -680,7 +682,7 @@ foo(); // Now foo is defined here ↥ back to top -## Q 2.6. What is the Temporal Dead Zone in ES6? +## Q. What is the Temporal Dead Zone in ES6? In ES6, **let** bindings are not subject to "variable hoisting", which means that **let** declarations do not move to the top of the current execution context. @@ -698,7 +700,7 @@ let aLet = 2; ↥ back to top -## Q 2.7. What is the purpose of double exclamation? +## Q. What is the purpose of double exclamation? The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. `0`, `null`, `undefined`, etc.), it will be `false`, otherwise, `true`. @@ -717,7 +719,7 @@ console.log(!!"text"); // true ↥ back to top -## Q 2.8. In JavaScript, what is the difference between `var x = 1` and `x = 1`? +## Q. In JavaScript, what is the difference between `var x = 1` and `x = 1`? `var x = 1`: @@ -803,7 +805,7 @@ console.log(x) // 1 ↥ back to top -## Q 2.9. How do you assign default values to variables? +## Q. How do you assign default values to variables? You can use the logical or operator `||` in an assignment expression to provide a default value. @@ -819,7 +821,7 @@ As per the above expression, variable 'a 'will get the value of 'c' only if 'b' ↥ back to top -## Q 2.10. What is the precedence order between local and global variables? +## Q. What is the precedence order between local and global variables? A local variable takes precedence over a global variable with the same name. @@ -845,7 +847,7 @@ Good Evening ↥ back to top -## Q 2.11. What is variable shadowing in javascript? +## Q. What is variable shadowing in javascript? Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed. @@ -871,7 +873,7 @@ Hoist(20); // 20 ↥ back to top -## Q 2.13. How do you swap variables using destructuring assignment? +## Q. How do you swap variables using destructuring assignment? ```js var x = 10, y = 20; @@ -888,9 +890,9 @@ console.log(y); // 10 ↥ back to top -## Q 2.14. What is scope chain in javascript? +## Q. What is scope chain in javascript? -The scope chain in JavaScript refers to the chain of nested scopes that a JavaScript program uses to look up variable and function references. When a variable or function is referenced in JavaScript code, the interpreter first looks for it in the current scope. If it's not found there, it moves up the scope chain to the next outer scope and looks for it there. It continues doing this until the variable or function is found or until it reaches the global scope. +The scope chain in JavaScript refers to the chain of nested scopes that a JavaScript program uses to look up variable and function references. When a variable or function is referenced in JavaScript code, the interpreter first looks for it in the current scope. If it\'s not found there, it moves up the scope chain to the next outer scope and looks for it there. It continues doing this until the variable or function is found or until it reaches the global scope. **Example:**: @@ -921,7 +923,7 @@ outer();
-## Q 3.1. What are data types in javascript? +## Q. What are data types in javascript? There are eight basic data types in JavaScript. @@ -970,7 +972,7 @@ console.log(number4); // Infinity const number5 = -3 / 0; console.log(number5); // -Infinity -// strings can't be divided by numbers +// strings can\'t be divided by numbers const number6 = "abc" / 3; console.log(number6); // NaN ``` @@ -1056,7 +1058,7 @@ const employee = { ↥ back to top -## Q 3.2. What is `undefined` property? +## Q. What is `undefined` property? The undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too. @@ -1075,7 +1077,7 @@ user = undefined ↥ back to top -## Q 3.3. What is difference between `null` vs `undefined`? +## Q. What is difference between `null` vs `undefined`? **Null:** @@ -1121,7 +1123,7 @@ console.log(typeof test2); // undefined ↥ back to top -## Q 3.4. What is Coercion in JavaScript? +## Q. What is Coercion in JavaScript? Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit. @@ -1154,7 +1156,7 @@ console.log(sum);
-## Q 4.1. What are various operators supported by javascript? +## Q. What are various operators supported by javascript? An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below, @@ -1213,7 +1215,7 @@ The assignment operators to assign values to variables with less key strokes. ↥ back to top -## Q 4.2. What are the bitwise operators available in javascript? +## Q. What are the bitwise operators available in javascript? Below are the list of bit-wise logical operators used in JavaScript @@ -1245,7 +1247,7 @@ Below are the list of bit-wise logical operators used in JavaScript ↥ back to top -## Q 4.3. What is the difference between == and === operators? +## Q. What is the difference between == and === operators? JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types, @@ -1280,7 +1282,7 @@ null === undefined // false ↥ back to top -## Q 4.4. What is typeof operator? +## Q. What is typeof operator? In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. @@ -1326,7 +1328,7 @@ console.log(typeof i); // "function" ↥ back to top -## Q 4.5. What is an Unary operator? +## Q. What is an Unary operator? The unary(+) operator is used to convert a variable to a number. If the variable cannot be converted, it will still become a number but with the value NaN. @@ -1348,7 +1350,7 @@ console.log(typeof a, typeof b, b); // string, number, NaN ↥ back to top -## Q 4.6. What is the purpose of delete operator? +## Q. What is the purpose of delete operator? The delete keyword is used to delete the property as well as its value. @@ -1363,7 +1365,7 @@ console.log(user); // {name: "Sadhika Chaudhuri"} ↥ back to top -## Q 4.7. What is a conditional operator in javascript? +## Q. What is a conditional operator in javascript? The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement. @@ -1385,7 +1387,7 @@ console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticat ↥ back to top -## Q 4.8. Can you apply chaining on conditional operator? +## Q. Can you apply chaining on conditional operator? Yes, you can apply chaining on conditional operator similar to if … else if … else if … else chain. @@ -1417,7 +1419,7 @@ function getValue(someParam) { ↥ back to top -## Q 4.9. What is the difference between `typeof` and `instanceof` operator? +## Q. What is the difference between `typeof` and `instanceof` operator? The `typeof` operator checks if a value has type of primitive type which can be one of `boolean`, `function`, `object`, `number`, `string`, `undefined`, `symbol`, or `bigint`. @@ -1447,7 +1449,7 @@ b instanceof String; // returns true ↥ back to top -## Q 4.10. What is the output of below spread operator array? +## Q. What is the output of below spread operator array? ```js [...'Hello'] @@ -1461,7 +1463,7 @@ b instanceof String; // returns true ↥ back to top -## Q 4.11. What is the nullish coalescing operator (`??`) in JavaScript? +## Q. What is the nullish coalescing operator (`??`) in JavaScript? The **nullish coalescing operator** (`??`) returns the right-hand side operand when the left-hand side operand is `null` or `undefined`. Otherwise, it returns the left-hand side operand. Unlike `||`, it does **not** treat `0`, `false`, or `""` as falsy. @@ -1498,7 +1500,7 @@ console.log(user.name); // 'Anonymous' ↥ back to top -## Q 4.12. What are logical assignment operators in JavaScript? +## Q. What are logical assignment operators in JavaScript? Logical assignment operators (ES2021) combine a logical operator with assignment. There are three: @@ -1547,7 +1549,7 @@ console.log(f); // 0 (0 is not null/undefined)
-## Q 5.1. How do you generate random integers? +## Q. How do you generate random integers? The `Math.random()` function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1). For example, if you want generate random integers between 1 to 100, the multiplication factor should be 100, @@ -1572,7 +1574,7 @@ console.log(getRandomNumber(10)); // returns a random integer from 1 to 10 ↥ back to top -## Q 5.2. What is isNaN? +## Q. What is isNaN? The `isNaN()` function determines whether a value is NaN ( Not a Number ) or not. This function returns `true` if the value equates to NaN. The `isNaN()` method converts the value to a number before testing it. @@ -1592,7 +1594,7 @@ Number.isNaN('Hello'); // false ↥ back to top -## Q 5.3. What is the purpose of isFinite function? +## Q. What is the purpose of isFinite function? The global `isFinite()` function determines whether the passed value is a finite number. It returns `false` if the value is `+infinity`, `-infinity`, or `NaN` (Not-a-Number), otherwise it returns true. @@ -1615,7 +1617,7 @@ Number.isFinite("123") // false ↥ back to top -## Q 5.4. Explain NEGATIVE_INFINITY in JavaScript? +## Q. Explain NEGATIVE_INFINITY in JavaScript? The `Number.NEGATIVE_INFINITY` property represents the negative Infinity value. @@ -1655,7 +1657,7 @@ console.log(Number.NEGATIVE_INFINITY === -2 * Number.MAX_VALUE); // true
-## Q 6.1. What is the difference between slice and splice? +## Q. What is the difference between slice and splice? **1. slice():** @@ -1694,7 +1696,7 @@ console.log(numbers); // Original array is mutated. | Slice | Splice | |---- | ---------| -| Doesn't modify the original array(immutable) | Modifies the original array(mutable) | +| Doesn\'t modify the original array(immutable) | Modifies the original array(mutable) | | Returns the subset of original array | Returns the deleted elements as array | | Used to pick the elements from array | Used to insert or delete elements to/from array| @@ -1704,7 +1706,7 @@ console.log(numbers); // Original array is mutated. ↥ back to top -## Q 6.2. How do you check whether a string contains a substring? +## Q. How do you check whether a string contains a substring? There are 3 fastest ways to check whether a string contains a substring or not, @@ -1751,7 +1753,7 @@ str.includes('Node', 5) //true ↥ back to top -## Q 6.3. How do you trim a string in javascript? +## Q. How do you trim a string in javascript? The `trim()` method removes whitespace from both sides of a string. JavaScript provides 3 simple functions on how to trim strings. @@ -1797,7 +1799,7 @@ console.log(phoneNumber.trimEnd()); // => " 80-555-123" ↥ back to top -## Q 6.4. What is eval function in javascript? +## Q. What is eval function in javascript? The `eval()` function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements. @@ -1831,7 +1833,7 @@ Warning: *Executing JavaScript from a string is an enormous security risk. It is ↥ back to top -## Q 6.5. How do you check if a string starts with another string? +## Q. How do you check if a string starts with another string? You can use `String.prototype.startsWith()` method to check if a string starts with another string or not. It is fully supported in all modern browsers. @@ -1848,7 +1850,7 @@ console.log(str.startsWith("World")); // false ↥ back to top -## Q 6.6. What are `replaceAll()`, `padStart()` and `padEnd()` string methods? +## Q. What are `replaceAll()`, `padStart()` and `padEnd()` string methods? **1. String.prototype.replaceAll():** @@ -1888,7 +1890,7 @@ console.log('42'.padEnd(5, '-')); // '42---'
-## Q 7.1. Explain arrays in JavaScript? +## Q. Explain arrays in JavaScript? JavaScript array is an object that represents a collection of similar type of elements. It can holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions. @@ -1939,7 +1941,7 @@ fruits.push("Grapes"); // Adds a new element (Grapes) to fruits ↥ back to top -## Q 7.2. What are associative arrays in javascript? +## Q. What are associative arrays in javascript? Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop. @@ -1982,7 +1984,7 @@ email = sakshi.memon@email.com ↥ back to top -## Q 7.3. Calculate the length of the associative array? +## Q. Calculate the length of the associative array? **Method 1:** Using `Object.keys().length` @@ -2029,7 +2031,7 @@ Object.getOwnPropertyNames(employee).length; // Output 3 ↥ back to top -## Q 7.4. What is the difference between Array and Array of Objects in JavaScript? +## Q. What is the difference between Array and Array of Objects in JavaScript? Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values. @@ -2084,7 +2086,7 @@ for (let key in employees) { ↥ back to top -## Q 7.5. Explain array methods [ join(), pop(), push(), shift(), unshift(), concat(), map(), filter(), reduce(), reduceRight(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex(), includes() ] +## Q. Explain array methods [ join(), pop(), push(), shift(), unshift(), concat(), map(), filter(), reduce(), reduceRight(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex(), includes() ] **1. array.join()**: @@ -2352,7 +2354,7 @@ console.log(numbers.findLastIndex(n => n > 10)); // Output: 4 ↥ back to top -## Q 7.6. What are the benefits of using spread syntax and how is it different from rest syntax? +## Q. What are the benefits of using spread syntax and how is it different from rest syntax? Spread operator or Spread Syntax allow us to expand the arrays and objects into elements in the case of an array and key-value pairs in the case of an object. @@ -2401,7 +2403,7 @@ The main difference between `rest` and `spread` is that the rest operator puts t |Spread Syntax | Rest Syntax | |------------------------|---------------------------------| |Spread operator as its name suggests it spreads or expands the content of the given element.| Rest Syntax is just the opposite of spread syntax it collects the data and stores that data in a variable which we can use further in our code.| -|It expands an Array in form of elements, while in key-value pairs in the case of Objects. | It collects the data in the developer's desired format.| +|It expands an Array in form of elements, while in key-value pairs in the case of Objects. | It collects the data in the developer\'s desired format.| |You may or may not use the strict mode inside the function containing the spread operator. | You can not use the strict mode inside function containing the rest operator.| |It will overwrite the identical properties inside two objects and replace the former with the latter. | It simply collects all properties and wraps them inside a container.| @@ -2411,7 +2413,7 @@ The main difference between `rest` and `spread` is that the rest operator puts t ↥ back to top -## Q 7.7. What is the difference between for..in and for..of? +## Q. What is the difference between for..in and for..of? Both `for..of` and `for..in` statements iterate over lists; the values iterated on are different though, `for..in` returns a **list of keys** on the object being iterated, whereas `for..of` returns a **list of values** of the numeric properties of the object being iterated. @@ -2440,7 +2442,7 @@ for (let i of list) { ↥ back to top -## Q 7.8. Can you give an example for destructuring an array? +## Q. Can you give an example for destructuring an array? Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables. @@ -2471,7 +2473,7 @@ console.log(b); // 10 ↥ back to top -## Q 7.9. What are default values in destructuring assignment? +## Q. What are default values in destructuring assignment? A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. @@ -2497,7 +2499,7 @@ console.log("k: " + k); // 6 **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/ecstatic-drake-iq971p?file=/src/index.js)** -## Q 7.10. When to use reduce(), map(), foreach() and filter() in JavaScript? +## Q. When to use reduce(), map(), foreach() and filter() in JavaScript? **1. forEach():** @@ -2575,7 +2577,7 @@ console.log(sum); // Output: 60 ↥ back to top -## Q 7.11. How do you define JSON arrays? +## Q. How do you define JSON arrays? JSON is an acronym for JavaScript Object Notation, and is "an open standard data interchange format". @@ -2607,7 +2609,7 @@ console.log(employees[0].name) // Kabir Dixit ↥ back to top -## Q 7.12. How to validate JSON Object in javascript? +## Q. How to validate JSON Object in javascript? `JSON.parse()` function will use string and converts to JSON object and if it parses invalidate JSON data, it throws an exception ( **Uncaught SyntaxError: Unexpected string in JSON** ). @@ -2631,7 +2633,7 @@ console.log(isValidJson("abc")); // false ↥ back to top -## Q 7.13. What is the purpose JSON stringify? +## Q. What is the purpose JSON stringify? When sending data to a web server, the data has to be in a string format. The `JSON.stringify()` method converts a JavaScript object or value to a JSON string format. @@ -2645,7 +2647,7 @@ console.log(JSON.stringify(user)); // {"name":"Shashi Meda","email":"shashi.meda ↥ back to top -## Q 7.14. How do you parse JSON string? +## Q. How do you parse JSON string? When receiving the data from a web server, the data is always in a string format. But you can convert this string value to javascript object using `JSON.parse()` method. @@ -2659,11 +2661,11 @@ console.log(JSON.parse(user));// {'name': 'Shashi Meda', 'email': 'shashi.meda@e ↥ back to top -## Q 7.15. What is the purpose of compare function while sorting arrays? +## Q. What is the purpose of compare function while sorting arrays? The purpose of the compare function is to define an alternative sort order. When the `sort()` function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. -If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. +If omitted, the array elements are converted to strings, then sorted according to each character\'s Unicode code point value. ```js const numbers = [1, 2, 5, 3, 4]; @@ -2678,7 +2680,7 @@ console.log(numbers); // [5, 4, 3, 2, 1] ↥ back to top -## Q 7.16. Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other? +## Q. Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other? To understand the differences between the two, Let us look at what each function does. @@ -2719,7 +2721,7 @@ The main difference between `.forEach` and `.map()` is that `.map()` returns a n ↥ back to top -## Q 7.17. What is unshift() method in JavaScript? +## Q. What is unshift() method in JavaScript? The `unshift()` method adds one or more elements to the beginning of an array and returns the new length of the array. @@ -2738,7 +2740,7 @@ console.log(numbers); // [40, 50, 10, 20, 30] ↥ back to top -## Q 7.18. What is a rest parameter? +## Q. What is a rest parameter? The rest parameter is used to represent an indefinite number of arguments as an array. The important point here is only the function\'s last parameter can be a "rest parameter". @@ -2764,7 +2766,7 @@ console.log(sum(10, 20, 30)); // 60 ↥ back to top -## Q 7.19. What happens if you do not use rest parameter as a last argument? +## Q. What happens if you do not use rest parameter as a last argument? The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. @@ -2791,13 +2793,13 @@ SyntaxError: Rest element must be last element ↥ back to top -## Q 7.20. What is difference between [] and new Array()? +## Q. What is difference between [] and new Array()? `[]` and `new Array()` are two different ways of creating an array, but they are functionally equivalent. The primary difference between them is in how they are created and in their behavior when used with certain methods. -`[]` is a shorthand for creating a new array. It is the preferred way to create an array in most cases, because it's more concise and easier to read. For example: +`[]` is a shorthand for creating a new array. It is the preferred way to create an array in most cases, because it\'s more concise and easier to read. For example: ```js const myArray = []; // create a new empty array @@ -2811,15 +2813,15 @@ const myOtherArray = new Array(3); // create a new array with a length of 3 const myThirdArray = new Array("a", "b", "c"); // create a new array with three elements ``` -One potential pitfall of using `new Array()` is that it can be ambiguous when you pass a single argument to the constructor. For example, `new Array(3)` creates an array with a length of 3, but `new Array("3")` creates an array with a single element, the string "3". This is because the argument is treated as the value of the first element when it's a non-negative integer, but as the length of the array when it's a string or a negative integer. +One potential pitfall of using `new Array()` is that it can be ambiguous when you pass a single argument to the constructor. For example, `new Array(3)` creates an array with a length of 3, but `new Array("3")` creates an array with a single element, the string "3". This is because the argument is treated as the value of the first element when it\'s a non-negative integer, but as the length of the array when it\'s a string or a negative integer. -In summary, `[]` is the preferred way to create a new array in JavaScript, while `new Array()` is an alternative way that can be used when you need more control over the array's length or contents. +In summary, `[]` is the preferred way to create a new array in JavaScript, while `new Array()` is an alternative way that can be used when you need more control over the array\'s length or contents. -## Q 7.21. What are `Array.from()`, `Array.of()` and `Array.isArray()` methods? +## Q. What are `Array.from()`, `Array.of()` and `Array.isArray()` methods? **1. Array.from():** @@ -2870,7 +2872,7 @@ console.log(Array.isArray(new Array())); // true
-## Q 8.1. What is a RegExp object? +## Q. What is a RegExp object? A regular expression is an object that describes a pattern of characters. @@ -2902,7 +2904,7 @@ let pattern = new RegExp(/ab+c/, 'i') // constructor with regular expression lit ↥ back to top -## Q 8.2. What are the string method available in regular expression? +## Q. What are the string method available in regular expression? Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the `exec()` and `test()` methods of `RegExp`, and with the `match()`, `matchAll()`, `replace()`, `replaceAll()`, `search()`, and `split()` methods of String. @@ -2948,7 +2950,7 @@ console.log(res2); // null ↥ back to top -## Q 8.3. What are modifiers in regular expression? +## Q. What are modifiers in regular expression? Modifiers can be used to perform case-insensitive and global searches. @@ -2994,7 +2996,7 @@ console.log(paragraph.match(pattern3)); // ["Lorem"] ↥ back to top -## Q 8.4. What are regular expression patterns? +## Q. What are regular expression patterns? Regular Expressions provided group of patterns in order to match characters. Basically they are categorized into 3 types, @@ -3061,7 +3063,7 @@ These are useful to define quantities ↥ back to top -## Q 8.5. How do you search a string for a pattern? +## Q. How do you search a string for a pattern? **1. Using test()** It searches a string for a pattern, and returns `true` or `false`, depending on the result. @@ -3089,7 +3091,7 @@ re2.exec("How are you?"); // ["you"] ↥ back to top -## Q 8.6. What is the purpose of exec method? +## Q. What is the purpose of exec method? The purpose of exec method is similar to test method but it returns a founded text as an object instead of returning true/false. @@ -3108,7 +3110,7 @@ console.log(pattern.exec("How are you?")); // ["you", index: 8, input: "How are ↥ back to top -## Q 8.7. How do you validate an email in javascript? +## Q. How do you validate an email in javascript? The `test()` method returns `true` if there is a match in the string with the regex pattern. The regular expression (regex) describes a sequence of characters used for defining a search pattern @@ -3141,7 +3143,7 @@ validateEmail(email2); // Not Valid ↥ back to top -## Q 8.8. How do you detect a mobile browser using regexp? +## Q. How do you detect a mobile browser using regexp? You can detect mobile browser by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage, @@ -3171,7 +3173,7 @@ function detectMobile() {
-## Q 9.1. What are the benefits of using arrow function over es5 function? +## Q. What are the benefits of using arrow function over es5 function? Arrows is a new syntax for functions, which brings several benefits: @@ -3233,7 +3235,7 @@ console.log(result); // 314 ↥ back to top -## Q 9.2. What is the benefit of using the arrow syntax for a method in a constructor? +## Q. What is the benefit of using the arrow syntax for a method in a constructor? The main advantage of using an arrow function as a method inside a constructor is that the value of `this` gets set at the time of the function creation and can\'t change after that. So, when the constructor is used to create a new object, `this` will always refer to that object. @@ -3271,7 +3273,7 @@ sayNameFromWindow2(); // John ↥ back to top -## Q 9.3. Difference between `Function`, `Method` and `Constructor` calls in JavaScript? +## Q. Difference between `Function`, `Method` and `Constructor` calls in JavaScript? **1. Functions:** The simplest usages of function call: @@ -3314,7 +3316,7 @@ Unlike function calls and method calls, a constructor call `new Employee('Drishy ↥ back to top -## Q 9.4. When you should not use arrow functions in ES6? +## Q. When you should not use arrow functions in ES6? An arrow function is a shorter syntax for a function expression and does not have its own **this, arguments, super, or new.target**. These function are best suited for non-method functions, and they cannot be used as constructors. @@ -3387,7 +3389,7 @@ const concat = (separator) => { ↥ back to top -## Q 9.5. What are the properties of function objects in javascript? +## Q. What are the properties of function objects in javascript? **JavaScript function objects** are used to define a piece of JavaScript code. This code can be called within a JavaScript code as and when required. @@ -3406,7 +3408,7 @@ const concat = (separator) => { ↥ back to top -## Q 9.6. What is a first class function? +## Q. What is a first class function? In javaScript, functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function **first-class function** in JavaScript. @@ -3474,7 +3476,7 @@ We are using double parentheses `()()` to invoke the returned function as well. ↥ back to top -## Q 9.7. What is a higher order function? +## Q. What is a higher order function? A Higher-Order function is a function that receives a function as an argument or returns the function as output. @@ -3529,7 +3531,7 @@ console.log("Sum: " + sum); // 60 ↥ back to top -## Q 9.8. What is a unary function? +## Q. What is a unary function? Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for single argument accepted by a function. @@ -3546,7 +3548,7 @@ console.log(unaryFunction(10)); // 20 ↥ back to top -## Q 9.9. What is currying function? +## Q. What is currying function? Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. @@ -3578,7 +3580,7 @@ console.log(addCurry(20)(20)(20)); // 60 ↥ back to top -## Q 9.10. What is a pure function? +## Q. What is a pure function? Pure functions are functions that accept an input and returns a value without modifying any data outside its scope(Side Effects). Its output or return value must depend on the input/arguments and pure functions must return a value. @@ -3617,14 +3619,14 @@ A function must pass two tests to be considered **pure**: * **Predictable**: It produces a predictable output for the same inputs. * **Readable**: Anyone reading the function as a standalone unit can understand its purpose completely. -* **Reusable**: Can reuse the function at multiple places of the source code without altering its and the caller's behavior. +* **Reusable**: Can reuse the function at multiple places of the source code without altering its and the caller\'s behavior. * **Testable**: We can test it as an independent unit. -## Q 9.11. What is memoization in JavaScript? +## Q. What is memoization in JavaScript? Memoization is a programming technique which attempts to increase a function\'s performance by **caching** its previously computed results. @@ -3661,7 +3663,7 @@ console.log(sum(10)); // Fetching from cache: 20 ↥ back to top -## Q 9.12. What is an arguments object? +## Q. What is an arguments object? The arguments object is an Array-like object ( `arguments` ) accessible inside functions that contains the values of the arguments passed to that function. @@ -3689,7 +3691,7 @@ sum(10, 20, 30); // returns 60 ↥ back to top -## Q 9.13. What is the way to find the number of parameters expected by a function? +## Q. What is the way to find the number of parameters expected by a function? The **length** property indicates the number of parameters expected by the function. @@ -3709,7 +3711,7 @@ console.log(fun2.length); // 2 ↥ back to top -## Q 9.14. What is the difference between Call, Apply and Bind? +## Q. What is the difference between Call, Apply and Bind? **1. Call:** invokes the function and allows you to pass in arguments one by one. @@ -3768,7 +3770,7 @@ sayEmployee2("Hello"); // Hello Aarush Krishna ↥ back to top -## Q 9.15. What is bind method in javascript? +## Q. What is bind method in javascript? The `bind()` method creates a new function, when invoked, has the `this` sets to a provided value. The `bind()` method allows an object to borrow a method from another object without making a copy of that method. This is known as function **borrowing** in JavaScript. @@ -3801,7 +3803,7 @@ console.log(fullName()); // Vasuda Sahota ↥ back to top -## Q 9.16. What is an anonymous function? +## Q. What is an anonymous function? An anonymous function is a function without a name. Anonymous functions are commonly assigned to a variable name or used as a callback function. @@ -3849,7 +3851,7 @@ add(10, 20); // 30 ↥ back to top -## Q 9.17. Explain the difference between `function foo() {}` and `var foo = function() {}`? +## Q. Explain the difference between `function foo() {}` and `var foo = function() {}`? **1. Function Declaration:** @@ -3882,7 +3884,7 @@ console.log(typeof foo); // undefined ↥ back to top -## Q 9.18. When to use function declarations and expressions in JavaScript? +## Q. When to use function declarations and expressions in JavaScript? **Function Declarations:** @@ -3927,7 +3929,7 @@ There are several different ways that function expressions become more useful th ↥ back to top -## Q 9.19. What is the difference between a method and a function in javascript? +## Q. What is the difference between a method and a function in javascript? **1. Function:** @@ -3975,7 +3977,7 @@ Here `employee` is an object and `getName` is a method which is associated with ↥ back to top -## Q 9.20. What is Function binding? +## Q. What is Function binding? Function binding ( `.bind()` ) is a method on the prototype of all functions in JavaScript. It allows to create a new function from an existing function, change the new function\'s `this` context, and provide any arguments you want the new function to be called with. The arguments provided to `bind` will precede any arguments that are passed to the new function when it is called. @@ -4006,7 +4008,7 @@ console.log(getName()); // Alisha Chhabra ↥ back to top -## Q 9.21. Explain how `this` works in JavaScript? +## Q. Explain how `this` works in JavaScript? The `this` keyword refers to an `object`. Which object depends on how this is being invoked (used or called). The `this` keyword refers to different objects depending on how it is used. @@ -4035,7 +4037,7 @@ const person = { ↥ back to top -## Q 9.22. What is generator in JS? +## Q. What is generator in JS? **Generator-Function:** @@ -4080,11 +4082,11 @@ gen.next().value; // 30 ↥ back to top -## Q 9.23. Compare Async-Await and Generators usage to achive same functionality? +## Q. Compare Async-Await and Generators usage to achive same functionality? **1. Generators/Yield:** -Generators are objects created by generator functions — functions with an * (asterisk) next to their name. The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. +Generators are objects created by generator functions — functions with an * (asterisk) next to their name. The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator\'s caller. It can be thought of as a generator-based version of the return keyword. ```js // Generator function @@ -4146,7 +4148,7 @@ asyncFunction(); ↥ back to top -## Q 9.24. How do you compare two date objects? +## Q. How do you compare two date objects? Two dates can be compared by converting them into numeric values using `date.getTime()` method to correspond to their time. Also, the relational operators `<`, `<=`, `>`, `>=` can be used to compare JavaScript dates. @@ -4178,7 +4180,7 @@ console.log(d3 < d4); // true ↥ back to top -## Q 9.25. What are closures? +## Q. What are closures? A closure is the combination of a function and the lexical environment within which that function was declared. i.e, it is an inner function that has access to the outer or enclosing function\'s variables. @@ -4246,7 +4248,7 @@ fun2(); ↥ back to top -## Q 9.26. What is callback() function in javascript? +## Q. What is callback() function in javascript? 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. @@ -4275,7 +4277,7 @@ The above example is a synchronous callback, as it is executed immediately. ↥ back to top -## Q 9.27. How to avoid callback hell in javascript? +## Q. How to avoid callback hell in javascript? **Callback hell** is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. Some people call it to be the **pyramid of doom**. @@ -4306,7 +4308,7 @@ doSomething(param1, param2, function(err, paramx){ ↥ back to top -## Q 9.28. How do you encode an URL? +## Q. How do you encode an URL? The encodeURI() function is used to encode complete URI which has special characters except (`,`, `/`, `?`, `:`, `@`, `&`, `=`, `+`, `$`, `#`) characters. @@ -4321,7 +4323,7 @@ console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B ↥ back to top -## Q 9.29. How do you decode an URL? +## Q. How do you decode an URL? The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI(). @@ -4341,7 +4343,7 @@ try { ↥ back to top -## Q 9.30. How function overloading works in JavaScript? +## Q. How function overloading works in JavaScript? Function overloading refers to the ability to define multiple functions with the same name but with different parameters. In many programming languages, the function to be executed is determined at compile time based on the parameters provided. However, in JavaScript, function overloading does not work in the same way because JavaScript functions can be called with any number and type of arguments. @@ -4369,7 +4371,7 @@ myFunction("Bob", "Charlie"); // output: "Hello Bob and Charlie" ↥ back to top -## Q 9.31. What is an IIFE (Immediately Invoked Function Expression)? +## Q. What is an IIFE (Immediately Invoked Function Expression)? An **IIFE** (Immediately Invoked Function Expression) is a JavaScript function that is defined and executed immediately after its creation. It creates a private scope so that variables inside it do not pollute the global scope. @@ -4401,8 +4403,8 @@ console.log(typeof message); // 'undefined' — private to the IIFE **Use cases:** * **Avoid global namespace pollution** — keeps variables local -* **Module pattern** — expose only what's needed through the return value -* **Initialization code** — logic that runs once and doesn't need to be callable later +* **Module pattern** — expose only what\'s needed through the return value +* **Initialization code** — logic that runs once and doesn\'t need to be callable later ```js // Counter using IIFE @@ -4425,11 +4427,233 @@ console.log(counter.value()); // 1 ↥ back to top +## Q. What is recursion in JavaScript? + +**Recursion** is a technique in which a function calls itself until it reaches a base case (a condition that stops further calls). Every recursive function must have a base case to avoid infinite loops and stack overflow errors. + +**Example 01:** Factorial + +```js +function factorial(n) { + if (n <= 1) return 1; // base case + return n * factorial(n - 1); // recursive call +} + +console.log(factorial(5)); // 120 +console.log(factorial(0)); // 1 +``` + +**Example 02:** Fibonacci + +```js +function fibonacci(n) { + if (n <= 1) return n; + return fibonacci(n - 1) + fibonacci(n - 2); +} + +console.log(fibonacci(7)); // 13 +``` + +**Example 03:** Flatten a nested array + +```js +function flattenArray(arr) { + return arr.reduce((acc, val) => + Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), + []); +} + +console.log(flattenArray([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5] +``` + +*Note: For deeply nested structures, iterative solutions with an explicit stack are preferred over recursion to avoid stack-overflow errors.* + + + +## Q. What are nested functions in JavaScript? + +A **nested function** is a function defined inside another function. The inner function has access to the outer function\'s variables and parameters through **closure**, but the outer function cannot access the inner function\'s variables. + +**Example:** + +```js +function outerFunction(outerValue) { + const outerVar = 'I am outer'; + + function innerFunction(innerValue) { + // inner can access outer\'s scope + console.log(outerVar); // 'I am outer' + console.log(outerValue); // passed argument + console.log(innerValue); // inner argument + } + + innerFunction('I am inner'); +} + +outerFunction('hello'); +``` + +**Use case — private helper functions:** + +```js +function processOrder(order) { + function validate(o) { + return o.quantity > 0 && o.price > 0; + } + + function calculateTotal(o) { + return o.quantity * o.price; + } + + if (!validate(order)) throw new Error('Invalid order'); + return calculateTotal(order); +} + +console.log(processOrder({ quantity: 3, price: 15 })); // 45 +``` + +The inner helpers `validate` and `calculateTotal` are private to `processOrder` and not accessible from outside. + + + +## Q. What are side effects in JavaScript functions? + +A **side effect** is any observable change that a function makes to the state outside its own scope — such as modifying a global variable, mutating an argument, writing to the DOM, or making a network request. + +**Functions with side effects:** + +```js +let count = 0; + +function increment() { + count++; // modifies external state — side effect +} + +increment(); +console.log(count); // 1 +``` + +**Pure function (no side effects):** + +```js +function add(a, b) { + return a + b; // no external mutation, same input always gives same output +} +``` + +**Common sources of side effects:** + +| Source | Example | +|--------|---------| +| Mutating arguments | `arr.push(item)` inside a function | +| Global state change | Modifying `window` or module-level variables | +| I/O operations | `console.log`, network calls, file writes | +| DOM manipulation | `document.getElementById('x').textContent = '...'` | + +**Why it matters:** Functions with side effects are harder to test, reason about, and reuse. Functional programming favors isolating side effects to the edges of a system while keeping the core logic pure. + + + +## Q. What is point-free style in JavaScript? + +**Point-free style** (also called *tacit programming*) is a way of defining functions without explicitly mentioning the arguments they operate on. Instead, functions are composed of other functions using combinators like `map`, `filter`, `reduce`, or a `compose`/`pipe` utility. + +**Without point-free:** + +```js +const numbers = [1, 2, 3, 4, 5]; + +// explicitly names the argument n +const doubled = numbers.map(n => n * 2); +``` + +**With point-free:** + +```js +const double = x => x * 2; + +// double is passed directly — no explicit argument mentioned +const doubled = numbers.map(double); +``` + +**More complex example:** + +```js +const trim = str => str.trim(); +const toUpperCase = str => str.toUpperCase(); +const words = str => str.split(' '); + +// Point-free pipeline using a pipe utility +const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x); + +const process = pipe(trim, toUpperCase, words); + +console.log(process(' hello world ')); // ['HELLO', 'WORLD'] +``` + +Point-free style leads to cleaner, more declarative code but can reduce readability when overused. + + + +## Q. What is function composition in JavaScript? + +**Function composition** is the process of combining two or more functions where the output of one function becomes the input of the next. It is a core concept in functional programming. + +**compose** applies functions right-to-left; **pipe** applies them left-to-right. + +**compose:** + +```js +const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); + +const add10 = x => x + 10; +const double = x => x * 2; +const square = x => x * x; + +// square( double( add10(5) ) ) => square(double(15)) => square(30) => 900 +const transform = compose(square, double, add10); +console.log(transform(5)); // 900 +``` + +**pipe (left-to-right):** + +```js +const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x); + +// add10(5) => double(15) => square(30) => 900 +const transform = pipe(add10, double, square); +console.log(transform(5)); // 900 +``` + +**Real-world example:** + +```js +const trim = str => str.trim(); +const toLower = str => str.toLowerCase(); +const removeSpaces = str => str.replace(/\s+/g, '-'); + +const slugify = pipe(trim, toLower, removeSpaces); + +console.log(slugify(' Hello World ')); // 'hello-world' +``` + + + ## # 10. EVENTS
-## Q 10.1. What is event handling in javascript? +## Q. What is event handling in javascript? The change in the state of an object is known as an **Event**. In html, there are various events which represents that some activity is performed by the user or by the browser. @@ -4490,7 +4714,7 @@ Some of the HTML event handlers are: ↥ back to top -## Q 10.2. How to create and trigger events in javascript? +## Q. How to create and trigger events in javascript? Events can be handled either through `addEventListener()` method or we can trigger events on individual components by defining specific JavaScript functions. @@ -4526,7 +4750,7 @@ document.addEventListener(event, function, phase) ↥ back to top -## Q 10.3. What is an event delegation? +## Q. What is an event delegation? Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the `event.target` property of the event object. @@ -4555,7 +4779,7 @@ Event Delegation is basically a pattern to handle events efficiently. Instead of ↥ back to top -## Q 10.4. What is an event flow? +## Q. What is an event flow? Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object. @@ -4572,7 +4796,7 @@ There are two ways of event flow ↥ back to top -## Q 10.5. What is event bubbling? +## Q. What is event bubbling? Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element. @@ -4598,7 +4822,7 @@ Event bubbling is a type of event propagation where the event first triggers on ↥ back to top -## Q 10.6. What is event capturing? +## Q. What is event capturing? Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element. @@ -4633,7 +4857,7 @@ Event capturing is a type of event propagation where the event is first captured ↥ back to top -## Q 10.7. How do you submit a form using JavaScript? +## Q. How do you submit a form using JavaScript? Generally, a form is submitted when the user presses a submit button. JavaScript provides the form object that contains the `submit()` method. Use the "id" of the form to get the form object. @@ -4656,7 +4880,7 @@ function handleSubmit() { ↥ back to top -## Q 10.8. What is the purpose of void(0)? +## Q. What is the purpose of void(0)? The `void(0)` is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the `undefined` primitive value. @@ -4674,7 +4898,7 @@ It is commonly used for HTML document that uses `href="JavaScript:void(0);"` wit ↥ back to top -## Q 10.9. What is the use of preventDefault method? +## Q. What is the use of preventDefault method? The `preventDefault()` method is used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link. @@ -4692,7 +4916,7 @@ document.getElementById("link").addEventListener("click", function(event) { ↥ back to top -## Q 10.10. What is the use of stopPropagation method? +## Q. What is the use of stopPropagation method? The `stopPropagation` method is used to stop the event from bubbling up the event chain. @@ -4720,7 +4944,7 @@ function secondFunc() { ↥ back to top -## Q 10.11. What is difference between stoppropagation, stopimmediatepropagation and preventdefault in javascript? +## Q. What is difference between stoppropagation, stopimmediatepropagation and preventdefault in javascript? **1. event.preventDefault()**: @@ -4740,7 +4964,7 @@ This method is used to stop the browser\'s default behavior when performing an a @@ -4777,7 +5001,7 @@ As a result, clicking on the div element will: ↥ back to top -## Q 10.12. What is the use of setTimeout? +## Q. What is the use of setTimeout? The `setTimeout()` method is used to call a function or evaluates an expression after a specified number of milliseconds. @@ -4799,7 +5023,7 @@ setTimeout(() => { ↥ back to top -## Q 10.13. What is the use of setInterval? +## Q. What is the use of setInterval? The `setInterval()` method is used to call a function or evaluates an expression at specified intervals (in milliseconds). The `setInterval()` method continues calling the function until `clearInterval()` is called, or the window is closed. @@ -4824,7 +5048,7 @@ function myTimer() { ↥ back to top -## Q 10.14. What is the purpose of clearTimeout method? +## Q. What is the purpose of clearTimeout method? The `clearTimeout()` function is used in javascript to clear the timeout which has been set by `setTimeout()` function before that. i.e, The return value of setTimeout() function is stored in a variable and it\'s passed into the `clearTimeout()` function to clear the timer. @@ -4861,7 +5085,7 @@ Stop ↥ back to top -## Q 10.15. What is the purpose of clearInterval method? +## Q. What is the purpose of clearInterval method? The `clearInterval()` function is used in javascript to clear the interval which has been set by `setInterval()` function. i.e, The return value returned by setInterval() function is stored in a variable and it\'s passed into the clearInterval() function to clear the interval. @@ -4898,7 +5122,7 @@ Stop ↥ back to top -## Q 10.16. What is the difference between document load and DOMContentLoaded events? +## Q. What is the difference between document load and DOMContentLoaded events? The `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images). @@ -4906,11 +5130,64 @@ The `DOMContentLoaded` event is fired when the initial HTML document has been co ↥ back to top +## Q. What is `requestAnimationFrame()` in JavaScript? + +`requestAnimationFrame()` is a browser API that tells the browser to call a specified function before the next repaint. It is the recommended way to create smooth animations and visual updates because it synchronizes with the browser\'s refresh rate (typically 60 fps), avoids unnecessary renders when the tab is hidden, and does not block the main thread. + +**Syntax:** + +```js +const id = requestAnimationFrame(callback); +cancelAnimationFrame(id); // cancel if needed +``` + +**Example — Smooth animation loop:** + +```js +let start = null; +const box = document.getElementById('box'); + +function animate(timestamp) { + if (!start) start = timestamp; + + const elapsed = timestamp - start; + const position = Math.min(elapsed / 10, 500); // move up to 500px over time + + box.style.transform = `translateX(${position}px)`; + + if (position < 500) { + requestAnimationFrame(animate); // schedule next frame + } +} + +requestAnimationFrame(animate); +``` + +**Comparison — `requestAnimationFrame` vs `setTimeout`:** + +| | `requestAnimationFrame` | `setTimeout` | +|--|------------------------|-------------| +| Tied to display refresh rate | ✅ Yes (usually 60 fps) | ❌ No | +| Paused in background tabs | ✅ Yes (saves battery) | ❌ No | +| Ideal for animations | ✅ | ⚠️ Can cause jank | +| Precision | High | Lower (can drift) | + +**Use cases:** + +* Smooth CSS/canvas animations +* Game loops +* Scroll-driven effects +* Any DOM update that should stay in sync with the browser\'s paint cycle + + + ## # 11. OBJECTS
-## Q 11.1. What are the possible ways to create objects in JavaScript? +## Q. What are the possible ways to create objects in JavaScript? **1. Object Constructor**: @@ -4991,7 +5268,7 @@ let object = new function() { ↥ back to top -## Q 11.2. What are the recommendations to create new object? +## Q. What are the recommendations to create new object? It is recommended to avoid creating new objects using `new Object()`. Instead you can initialize values based on it is type to create the objects. @@ -5019,7 +5296,7 @@ let obj7 = function(){}; ↥ back to top -## Q 11.3. What are the different ways to access object properties? +## Q. What are the different ways to access object properties? There are 3 possible ways for accessing the property of an object. @@ -5045,7 +5322,7 @@ objectName[expression] ↥ back to top -## Q 11.4. How to check if an object is an array or not? +## Q. How to check if an object is an array or not? The `Array.isArray()` method determines whether an object is an array. This function returns `true` if the object is an array, and `false` if not. @@ -5075,7 +5352,7 @@ The `Array.isArray()` method determines whether an object is an array. This func ↥ back to top -## Q 11.5. Can you give an example for destructuring an object? +## Q. Can you give an example for destructuring an object? Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct variables. @@ -5101,7 +5378,7 @@ console.log(job); // Developer ↥ back to top -## Q 11.6. How do you clone an object in JavaScript? +## Q. How do you clone an object in JavaScript? Using the object spread operator `...`, the object own enumerable properties can be copied into the new object. This creates a shallow clone of the object. @@ -5195,7 +5472,7 @@ John ↥ back to top -## Q 11.7. How do you copy properties from one object to other? +## Q. How do you copy properties from one object to other? You can use `Object.assign()` method which is used to copy the values and properties from one or more source objects to a target object. It returns the target object which has properties and values copied from the target object. The syntax would be as below, @@ -5221,7 +5498,7 @@ As observed in the above code, there is a common property(`b`) from source to ta ↥ back to top -## Q 11.8. What is the difference between native, host and user objects? +## Q. What is the difference between native, host and user objects? **1. Native Objects**: @@ -5239,7 +5516,7 @@ Are objects defined in the javascript code. For example, User object created for ↥ back to top -## Q 11.9. What are the properties of Intl object? +## Q. What are the properties of Intl object? The `Intl` object is the namespace for the ECMAScript Internationalization API that provides language number formatting, string comparison, and date/time formatting. @@ -5387,7 +5664,7 @@ console.log(dtfMyNewLocale2.format(now2)); // 5/17/2022 ↥ back to top -## Q 11.10. How do you convert date to another timezone in javascript? +## Q. How do you convert date to another timezone in javascript? The `.toLocaleString()` method to convert date in one timezone to another. @@ -5401,7 +5678,7 @@ console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); //29/06/2019, 0 ↥ back to top -## Q 11.11. Explain the difference between mutable and immutable objects? +## Q. Explain the difference between mutable and immutable objects? A mutable object is an object whose state can be modified after it is created. An immutable object is an object whose state cannot be modified after it is created. @@ -5411,7 +5688,7 @@ In JavaScript numbers, strings, null, undefined and Booleans are primitive types ↥ back to top -## Q 11.12. How to create immutable object in javascript +## Q. How to create immutable object in javascript In JavaScript, some built-in types (numbers, strings) are immutable, but custom objects are generally mutable. Some built-in immutable JavaScript objects are `Math`, `Date`. @@ -5517,7 +5794,7 @@ console.log(myCar.batteryLife); // 300 ↥ back to top -## Q 11.13. How do you determine whether object is frozen or not? +## Q. How do you determine whether object is frozen or not? `Object.isFrozen()` method is used to determine if an object is frozen or not. An object is frozen if all of the below conditions hold true, @@ -5538,7 +5815,7 @@ console.log(Object.isFrozen(object)); ↥ back to top -## Q 11.14. How can you achieve immutability in your own code? +## Q. How can you achieve immutability in your own code? For "mutating" objects, use the spread operator, `Object.assign`, `Array.concat()`, etc., to create new objects instead of mutate the original object. @@ -5561,7 +5838,7 @@ const alienAditya = { ...aditya, race: "alien" }; // {race: "alien", name: "Adit ↥ back to top -## Q 11.15. What is the drawback of declaring methods directly in JavaScript objects? +## Q. What is the drawback of declaring methods directly in JavaScript objects? One of the drawback of declaring methods directly in JavaScript objects is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object. @@ -5580,7 +5857,7 @@ const Employee = function (name, company, salary) }; }; -// we can also create method in Employee's prototype: +// we can also create method in Employee\'s prototype: Employee.prototype.formatSalary2 = function () { return "$ " + this.salary; }; @@ -5598,7 +5875,7 @@ Here, each instance variable `emp1`, `emp2` has own copy of `formatSalary` metho ↥ back to top -## Q 11.16. How do you compare Object and Map? +## Q. How do you compare Object and Map? **1. Object:** @@ -5669,7 +5946,7 @@ myMap.get(function () {}); // undefined, because keyFunc !== function () {} ↥ back to top -## Q 11.17. What is shallow copy and deep copy in javascript? +## Q. What is shallow copy and deep copy in javascript? **1. Shallow Copy:** @@ -5726,7 +6003,7 @@ console.log(newObj); // { a: 10, b: { c: 20 } } ↥ back to top -## Q 11.18. Write a function called deepClone which takes an object and creates a object copy of it? +## Q. Write a function called deepClone which takes an object and creates a object copy of it? **Modern approach — using `structuredClone()` (ES2022):** @@ -5772,7 +6049,7 @@ function deepClone(object) { ↥ back to top -## Q 11.19. Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object? +## Q. Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object? ```js var objectLit = {foo : 'Bar'}; @@ -5797,7 +6074,7 @@ function Clone(object){ ↥ back to top -## Q 11.20. How do you check if a key exists in an object? +## Q. How do you check if a key exists in an object? **1. Using `in` operator:** @@ -5814,7 +6091,7 @@ and If you want to check if a key doesn\'t exist, remember to use parenthesis, ```js const obj = { not_key: undefined }; -console.log(!("key" in obj)); // true if "key" doesn't exist in object +console.log(!("key" in obj)); // true if "key" doesn\'t exist in object ``` **2. Using `hasOwnProperty()` method:** @@ -5844,7 +6121,7 @@ console.log(Object.hasOwn(obj, "missing")); // false ↥ back to top -## Q 11.21. How do you loop through or enumerate javascript object? +## Q. How do you loop through or enumerate javascript object? You can use the `for-in` loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn\'t come from the prototype using `Object.hasOwn()` (ES2022) or the older `hasOwnProperty()` method. @@ -5866,7 +6143,7 @@ for (const key in object) { ↥ back to top -## Q 11.22. How do you test for an empty object? +## Q. How do you test for an empty object? **a. Using Object keys(ECMA 5+):** You can use object keys length along with constructor type. @@ -5884,7 +6161,82 @@ Object.entries(obj).length === 0 && obj.constructor === Object ↥ back to top -## Q 11.23. What is a proxy object? +## Q. What is prototype pollution in JavaScript? + +**Prototype pollution** is a security vulnerability where an attacker is able to inject properties into a JavaScript object\'s prototype (`Object.prototype`), causing those properties to appear on **every** object in the application. This can lead to denial-of-service, property injection, or remote code execution. + +**How it happens:** + +Many utility functions (deep merge, clone, set-by-path) use bracket-notation assignment with user-controlled keys. If the key is `__proto__`, `constructor`, or `prototype`, the attacker can modify `Object.prototype`. + +```js +// Vulnerable deep merge +function merge(target, source) { + for (const key in source) { + if (typeof source[key] === 'object') { + target[key] = {}; + merge(target[key], source[key]); + } else { + target[key] = source[key]; + } + } +} + +const malicious = JSON.parse('{"__proto__": {"isAdmin": true}}'); +merge({}, malicious); + +// Now EVERY object has isAdmin: true +const user = {}; +console.log(user.isAdmin); // true ← prototype polluted! +``` + +**How to prevent it:** + +```js +// 1. Use Object.create(null) for config/merge targets — no prototype to pollute +const safe = Object.create(null); + +// 2. Check for dangerous keys before assignment +function safeMerge(target, source) { + for (const key of Object.keys(source)) { + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + continue; // skip dangerous keys + } + if (typeof source[key] === 'object' && source[key] !== null) { + target[key] = target[key] || {}; + safeMerge(target[key], source[key]); + } else { + target[key] = source[key]; + } + } +} + +// 3. Use Object.freeze(Object.prototype) in security-critical code +Object.freeze(Object.prototype); + +// 4. Use structuredClone() or JSON.parse(JSON.stringify()) for deep cloning +// instead of custom recursive merges + +// 5. Use well-maintained libraries (lodash >= 4.17.21 patches this) +``` + +**Detection:** + +Use `Object.hasOwn(obj, key)` instead of `key in obj` to avoid reading polluted prototype properties: + +```js +// Vulnerable +if ('isAdmin' in user) { ... } // reads prototype chain + +// Safe +if (Object.hasOwn(user, 'isAdmin')) { ... } // own property only +``` + + + +## Q. What is a proxy object? The `Proxy` object allows to create an object that can be used in place of the original object, but which may redefine fundamental `Object` operations like getting, setting, and defining properties. @@ -5954,7 +6306,7 @@ There are many real-world applications for Proxies ↥ back to top -## Q 11.24. What is Reflection in JavaScript? +## Q. What is Reflection in JavaScript? Reflection is defined as the ability of a program to inspect and modify its structure and behavior at runtime. `Reflect` is not a function object. `Reflect` helps with forwarding default operations from the handler to the target. @@ -5980,7 +6332,7 @@ console.log(index); // 4 ↥ back to top -## Q 11.25. How do you display the current date in javascript? +## Q. How do you display the current date in javascript? You can use `new Date()` to generate a new Date object containing the current date and time. @@ -6004,7 +6356,7 @@ document.write(today); ↥ back to top -## Q 11.26. How do you add a key value pair in javascript? +## Q. How do you add a key value pair in javascript? There are two possible solutions to add new properties to an object. Let us take a simple object to explain these solutions. @@ -6031,7 +6383,7 @@ obj["key3"] = "value3"; ↥ back to top -## Q 11.27. How do you check whether an object can be extendable or not? +## Q. How do you check whether an object can be extendable or not? The `Object.isExtensible()` method is used to determine if an object is extensible or not. i.e, Whether it can have new properties added to it or not. @@ -6057,7 +6409,7 @@ console.log(Object.isExtensible(person)); // false ↥ back to top -## Q 11.28. How to compare two objects in javascript? +## Q. How to compare two objects in javascript? Objects are reference types so you can\'t just use `===` or `==` to compare 2 objects. One quick way to compare if 2 objects have the same key value, is using `JSON.stringify()`. Another way is using Lodash `.isEqual()` function. @@ -6080,7 +6432,7 @@ _.isEqual(obj1, obj2); // true ↥ back to top -## Q 11.29. How do you get enumerable key and value pairs? +## Q. How do you get enumerable key and value pairs? The `Object.entries()` method is used to return an array of a given object own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a `for...in` loop. Let us see the functionality of object.entries() method in an example, @@ -6102,7 +6454,7 @@ for (let [key, value] of Object.entries(object)) { ↥ back to top -## Q 11.30. What is the main difference between Object.values and Object.entries method? +## Q. What is the main difference between Object.values and Object.entries method? The `Object.values()` method\'s behavior is similar to `Object.entries()` method but it returns an array of values instead [key,value] pairs. @@ -6122,7 +6474,7 @@ for (let value of Object.values(object)) { ↥ back to top -## Q 11.31. How can you get the list of keys of any object? +## Q. How can you get the list of keys of any object? You can use `Object.keys()` method which is used return an array of a given object\'s own property names, in the same order as we get with a normal loop. For example, you can get the keys of a user object, @@ -6140,7 +6492,7 @@ console.log(Object.keys(user)); //['name', 'gender', 'age'] ↥ back to top -## Q 11.32. What is difference between array[] vs Object()? +## Q. What is difference between array[] vs Object()? * `[]` is declaring an array. * `{}` is declaring an object. @@ -6167,7 +6519,7 @@ An array is an object so it has all the same capabilities of an object plus a bu ↥ back to top -## Q 11.33. What is difference between `{}` vs `new Object()`? +## Q. What is difference between `{}` vs `new Object()`? **1. Object Literal Syntax (`{}`):** @@ -6224,7 +6576,7 @@ In general, it is recommended to use object literal syntax (`{}`) for creating o ↥ back to top -## Q 11.34. What is the `Object.fromEntries()` method? +## Q. What is the `Object.fromEntries()` method? `Object.fromEntries()` transforms a list of key-value pairs (such as an array of `[key, value]` pairs or a `Map`) into a plain object. It is the inverse of `Object.entries()`. @@ -6270,7 +6622,7 @@ console.log(doubled); // { apple: 3, banana: 1.5, cherry: 6 }
-## Q 12.1. What is the difference between window and document object? +## Q. What is the difference between window and document object? **1. Window Object**: @@ -6291,8 +6643,8 @@ window.property_name; |document |Returns the Document object for the window.| |frames |Returns all window objects running in the window.| |history |Returns the History object for the window.| -|innerHeight |Returns the height of the window's content area (viewport) including scrollbars| -|innerWidth |Returns the width of a window's content area (viewport) including scrollbars| +|innerHeight |Returns the height of the window\'s content area (viewport) including scrollbars| +|innerWidth |Returns the width of a window\'s content area (viewport) including scrollbars| |localStorage |Allows to save key/value pairs in a web browser. Stores the data with no expiration date| |location |Returns the Location object for the window.| |navigator |Returns the Navigator object for the window.| @@ -6329,7 +6681,7 @@ document.property_name; |---------------------|------------------------------------| |addEventListener() |Attaches an event handler to the document| |baseURI |Returns the absolute base URI of a document| -|body |Sets or returns the document's body (the `` element)| +|body |Sets or returns the document\'s body (the `` element)| |characterSet |Returns the character encoding for the document| |close() |Closes the output stream previously opened with document.open()| |cookie |Returns all name/value pairs of cookies in the document| @@ -6372,7 +6724,7 @@ document.property_name; ↥ back to top -## Q 12.2. How do you access history in javascript? +## Q. How do you access history in javascript? The `window.history` object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the `back()`, `forward()`, and `go()` methods. The `history.length` returns the number of URLs in the history stack. @@ -6418,7 +6770,7 @@ history.length ↥ back to top -## Q 12.3. How do you find operating system details? +## Q. How do you find operating system details? The `window.navigator` object contains information about the visitor\'s browser os details. Some of the OS properties are avaialble under platform property, @@ -6446,7 +6798,7 @@ VM87:8 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like ↥ back to top -## Q 12.4. How do you detect a browser language preference? +## Q. How do you detect a browser language preference? You can use navigator object to detect a browser language preference as below, @@ -6462,7 +6814,7 @@ console.log(language); ↥ back to top -## Q 12.5. What is BOM? +## Q. What is BOM? The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It consists of the objects navigator, history, screen, location and document which are children of window. The Browser Object Model is not standardized and can change based on different browsers. @@ -6474,7 +6826,7 @@ The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It co ↥ back to top -## Q 12.6. How do you redirect new page in javascript? +## Q. How do you redirect new page in javascript? To redirect to a new URL or page, you assign the new URL to the `location.href` property or use the `location.assign()` method. The `location.replace()` method does redirect to a new URL but does not create an entry in the history stack of the browser. @@ -6492,7 +6844,7 @@ function redirect() { ↥ back to top -## Q 12.7. How to get the current url with javascript? +## Q. How to get the current url with javascript? The `window.location` object can be used to get the current page address (URL) and to redirect the browser to a new page. You can also use `document.URL` for **read-only** purpose. @@ -6522,7 +6874,7 @@ console.log('location.href', window.location.href); // Returns full URL ↥ back to top -## Q 12.8. How to get query string values in javascript? +## Q. How to get query string values in javascript? The `URLSearchParams()` provides an interface to work with query string parameters. The `has()` method of the `URLSearchParams()` determines if a parameter with a specified name exists. @@ -6587,7 +6939,7 @@ for (const entry of urlParams.entries()) { ↥ back to top -## Q 12.9. What is difference between window.frames, window.parent and window.top in JavaScript? +## Q. What is difference between window.frames, window.parent and window.top in JavaScript? * **window.frames** – the collection of "children" windows (for nested frames). * **window.parent** – property returns the immediate parent of the current window @@ -6597,7 +6949,7 @@ for (const entry of urlParams.entries()) { ↥ back to top -## Q 12.10. What are the properties used to get size of window? +## Q. What are the properties used to get size of window? **1. The screen size:** @@ -6710,7 +7062,7 @@ document.onload = function ... ↥ back to top -## Q 12.12. What is the difference between document load event and document domcontentloaded event? +## Q. What is the difference between document load event and document domcontentloaded event? **1. DOMContentLoaded:** @@ -6740,11 +7092,11 @@ document.addEventListener("load", function(e) { ↥ back to top -## Q 12.13. What do you understand by Screen objects? +## Q. What do you understand by Screen objects? -* **window**: is the execution context and global object for that context's JavaScript +* **window**: is the execution context and global object for that context\'s JavaScript * **document**: contains the DOM, initialized by parsing HTML -* **screen**: The screen object contains information about the visitor's screen. +* **screen**: The screen object contains information about the visitor\'s screen. | Property | Description | @@ -6762,7 +7114,7 @@ document.addEventListener("load", function(e) { ↥ back to top -## Q 12.14. How to change style of html element using javascript? +## Q. How to change style of html element using javascript? Below is the syntax for manipulating the style property on an HTML element using JavaScript: @@ -6800,7 +7152,7 @@ for (i = 0; i < x.length; i++) { ↥ back to top -## Q 12.15. How do you print the contents of web page? +## Q. How do you print the contents of web page? The window object provided print() method which is used to prints the contents of the current window. It opens Print dialog box which lets you choose between various printing options. @@ -6816,7 +7168,7 @@ The window object provided print() method which is used to prints the contents o ↥ back to top -## Q 12.16. How do I modify the url without reloading the page? +## Q. How do I modify the url without reloading the page? The `window.localtion.url` property will be helpful to modify the url but it reloads the page. HTML5 introduced the `history.pushState()` and `history.replaceState()` methods, which allow you to add and modify history entries, respectively. @@ -6830,7 +7182,7 @@ window.history.pushState('newPage', 'Title', '/newPage.html'); ↥ back to top -## Q 12.18. What is the difference between an attribute and a property? +## Q. What is the difference between an attribute and a property? Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value, @@ -6857,7 +7209,7 @@ console.log(input.value); // Good evening ↥ back to top -## Q 12.19. What is the difference between firstChild and firstElementChild? +## Q. What is the difference between firstChild and firstElementChild? **1. firstChild:** @@ -6899,7 +7251,7 @@ let list = document.getElementById("myList").firstElementChild.innerHTML; // Cof ↥ back to top -## Q 12.20. What is difference between document.getElementById() and document.querySelector()? +## Q. What is difference between document.getElementById() and document.querySelector()? **1. document.getElementById():** @@ -6931,7 +7283,7 @@ element = document.querySelectorAll(selectors); ↥ back to top -## Q 12.21. Name the two functions that are used to create an HTML element dynamically? +## Q. Name the two functions that are used to create an HTML element dynamically? In an HTML document, the `document.createElement()` method creates the HTML element specified by tagName. @@ -7001,7 +7353,7 @@ function removeElement(elementId) { ↥ back to top -## Q 12.22. What is difference between append() vs appendChild()? +## Q. What is difference between append() vs appendChild()? * ParentNode.append() allows you to also append DOMString object, whereas Node.appendChild() only accepts Node objects. * ParentNode.append() has no return value, whereas Node.appendChild() returns the appended Node object. @@ -7019,7 +7371,7 @@ document.getElementById("yourId").appendChild(p); ↥ back to top -## Q 12.23. How to check if page is fully loaded using javascript? +## Q. How to check if page is fully loaded using javascript? ```js if (document.readyState === 'complete') { @@ -7030,7 +7382,7 @@ if (document.readyState === 'complete') { ↥ back to top -## Q 12.24. What is a web-storage event and its event handler? +## Q. What is a web-storage event and its event handler? The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below @@ -7057,11 +7409,122 @@ if (typeof(Storage) !== "undefined") { ↥ back to top +## Q. What is the difference between localStorage, sessionStorage, cookies, and IndexedDB? + +All four are browser-side storage mechanisms, but they differ in lifetime, scope, capacity, and use case. + +| Feature | `localStorage` | `sessionStorage` | Cookies | IndexedDB | +|---------|--------------|----------------|---------|-----------| +| **Lifetime** | Until explicitly cleared | Until tab/window closes | Configurable (session or expiry date) | Until explicitly deleted | +| **Scope** | Origin (protocol + domain + port) | Origin + tab | Domain + path | Origin | +| **Sent to server** | Never | Never | With every HTTP request | Never | +| **Storage limit** | ~5–10 MB | ~5 MB | ~4 KB per cookie | Hundreds of MB | +| **API type** | Synchronous | Synchronous | Synchronous | Asynchronous (event-based) | +| **Data type** | Strings only | Strings only | Strings only | Structured data, blobs | +| **Accessible in Service Worker** | No | No | No | Yes | + +**localStorage example:** + +```js +// Persist across sessions +localStorage.setItem('theme', 'dark'); +const theme = localStorage.getItem('theme'); // 'dark' +localStorage.removeItem('theme'); +localStorage.clear(); +``` + +**sessionStorage example:** + +```js +// Data lives only for the tab\'s lifetime +sessionStorage.setItem('formData', JSON.stringify({ step: 2 })); +const formData = JSON.parse(sessionStorage.getItem('formData')); +``` + +**Cookie example:** + +```js +// Set a cookie that expires in 7 days +document.cookie = 'user=Alice; max-age=604800; path=/; Secure; SameSite=Strict'; + +// Read all cookies +console.log(document.cookie); // 'user=Alice' +``` + +**When to use which:** + +* `localStorage` — user preferences, theme, language (persistent, no server needed). +* `sessionStorage` — multi-step form state, temporary auth tokens per tab. +* `Cookies` — authentication tokens sent with every request, CSRF tokens, tracking (can be made `HttpOnly` for security). +* `IndexedDB` — large structured datasets, offline apps, file/blob storage. + + + +## Q. What is the Intersection Observer API? + +The **Intersection Observer API** provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or the viewport. It is commonly used for lazy loading images, infinite scrolling, and triggering animations when elements come into view — all without scroll event listeners that can hurt performance. + +**Syntax:** + +```js +const observer = new IntersectionObserver(callback, options); +observer.observe(targetElement); +``` + +**Options:** + +| Option | Description | Default | +|--------|-------------|---------| +| `root` | Ancestor to use as viewport (`null` = browser viewport) | `null` | +| `rootMargin` | Margin around root (like CSS margin) | `'0px'` | +| `threshold` | Ratio of target visibility to trigger callback (0–1 or array) | `0` | + +**Example — Lazy loading images:** + +```js +const images = document.querySelectorAll('img[data-src]'); + +const observer = new IntersectionObserver((entries) => { + entries.forEach(entry => { + if (entry.isIntersecting) { + const img = entry.target; + img.src = img.dataset.src; // load the real image + img.removeAttribute('data-src'); + observer.unobserve(img); // stop observing once loaded + } + }); +}, { rootMargin: '200px' }); // start loading 200px before visible + +images.forEach(img => observer.observe(img)); +``` + +**Example — Infinite scroll:** + +```js +const sentinel = document.querySelector('#load-more-sentinel'); + +const observer = new IntersectionObserver((entries) => { + if (entries[0].isIntersecting) { + loadMoreItems(); + } +}, { threshold: 1.0 }); + +observer.observe(sentinel); +``` + +*Note: Intersection Observer is far more performant than listening to `scroll` events because it does not run on the main thread.* + + + # # 13. CLASSES
-## Q 13.1. Explain how prototypal inheritance works? +## Q. Explain how prototypal inheritance works? The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. @@ -7082,7 +7545,7 @@ In the given example, there are two objects **ParentUser** and **ChildUser**. Th let ParentUser = { talk: true, Canfly() { - return "Sorry, Can't fly"; + return "Sorry, Can\'t fly"; }, }; @@ -7090,7 +7553,7 @@ let ParentUser = { let ChildUser = { CanCode: true, CanCook() { - return "Can't say"; + return "Can\'t say"; }, // Inheriting the properties and methods of Parent Object @@ -7116,7 +7579,7 @@ console.log("Can a User cook?: " + ChildUser.CanCook()); ↥ back to top -## Q 13.2. What is the difference between prototype and __proto__ in JavaScript? +## Q. What is the difference between prototype and __proto__ in JavaScript? **1. Proto**: @@ -7185,7 +7648,7 @@ console.log(employee.getName()); ↥ back to top -## Q 13.3. What are the differences between ES6 class and ES5 function constructors? +## Q. What are the differences between ES6 class and ES5 function constructors? Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics. @@ -7208,7 +7671,7 @@ function Student(name, studentId) { // Call constructor of superclass to initialize superclass-derived members. Person.call(this, name); - // Initialize subclass's own members. + // Initialize subclass\'s own members. this.studentId = studentId; } @@ -7234,7 +7697,7 @@ It\'s much more verbose to use inheritance in ES5 and the ES6 version is easier ↥ back to top -## Q 13.4. What is class expression in es6 class? +## Q. What is class expression in es6 class? A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class\'s body. However, it can be accessed via the name property. @@ -7266,7 +7729,7 @@ console.log(Triangle.name); // TriangleClass ↥ back to top -## Q 13.5. What is difference between private, public and static variables? +## Q. What is difference between private, public and static variables? Private variables can be accessed by all the members (functions and variables) of the owner object but not by any other object. Public variables can be accessed by all the members of the owner as well as other objects that can access the owner. Static variables are related to a class. They come into existence as soon as a class come into existence. @@ -7305,7 +7768,7 @@ console.log(MyClass.staticProperty); // I am static! ↥ back to top -## Q 13.6. What is difference between Classic Inheritance and Prototypical Inheritance? +## Q. What is difference between Classic Inheritance and Prototypical Inheritance? **1. Class Inheritance**: @@ -7351,7 +7814,7 @@ console.log(circle.circumference()); // 31.41592653589793 ↥ back to top -## Q 13.7. How do you create an object with prototype? +## Q. How do you create an object with prototype? The `Object.create()` method is used to create a new object with the specified prototype object and properties. i.e, It uses existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties. @@ -7376,7 +7839,7 @@ admin.printInfo(); // My name is Disha Choudhry ↥ back to top -## Q 13.8. How to use constructor functions for inheritance in JavaScript? +## Q. How to use constructor functions for inheritance in JavaScript? Let say we have `Person` class which has name, age, salary properties and **incrementSalary()** method. @@ -7421,7 +7884,7 @@ console.log(employee instanceof Employee); // true ↥ back to top -## Q 13.9. What is prototype chain? +## Q. What is prototype chain? **Prototype chaining** is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through `Object.getPrototypeOf(object)` or `__proto__` property whereas prototype on constructors function is available through **Object.prototype**. @@ -7452,7 +7915,7 @@ person.getFullName(); // Vanya Dayal ↥ back to top -## Q 13.10. What are javascript accessors? +## Q. What are javascript accessors? ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses `get` keyword whereas Setters uses `set` keyword. @@ -7478,7 +7941,7 @@ console.log(user.lang); // setter used to set lang as fr ↥ back to top -## Q 13.11. How do you define property on Object constructor? +## Q. How do you define property on Object constructor? The Object.defineProperty() static method is used to define a new property directly on an object, or modifies an existing property on an object, and returns the object. @@ -7499,7 +7962,7 @@ newObject.newProperty = 200; // It throws an error in strict mode due to writabl ↥ back to top -## Q 13.12. What is the difference between get and defineProperty? +## Q. What is the difference between get and defineProperty? Both has similar results until unless you use classes. If you use `get` the property will be defined on the prototype of the object whereas using `Object.defineProperty()` the property will be defined on the instance it is applied to. @@ -7507,7 +7970,7 @@ Both has similar results until unless you use classes. If you use `get` the prop ↥ back to top -## Q 13.13. What are the advantages of Getters and Setters? +## Q. What are the advantages of Getters and Setters? Below are the list of benefits of Getters and Setters, @@ -7521,7 +7984,7 @@ Below are the list of benefits of Getters and Setters, ↥ back to top -## Q 13.14. Can I add getters and setters using defineProperty method? +## Q. Can I add getters and setters using defineProperty method? Yes, You can use `Object.defineProperty()` method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and substract properties, @@ -7554,7 +8017,7 @@ console.log(obj.decrement); //5 ↥ back to top -## Q 13.15. What is a decorator? +## Q. What is a decorator? A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. @@ -7582,7 +8045,7 @@ console.log(User.isAdmin); // false ↥ back to top -## Q 13.16. What are private class fields in JavaScript? +## Q. What are private class fields in JavaScript? Private class fields (ES2022) use the `#` prefix to declare fields that are only accessible from inside the class body. They are a true hard private — not accessible via `obj['#field']` or any workaround. @@ -7657,7 +8120,7 @@ console.log(Counter.getCount()); // 2
-## Q 14.1. What is an error object? +## Q. What is an error object? An error object is a built in error object that provides error information when an error occurs. It has two properties: **name** and **message**. @@ -7681,7 +8144,7 @@ ReferenceError: greeting is not defined ↥ back to top -## Q 14.2. Define the various types of errors which occur in JavaScript? +## Q. Define the various types of errors which occur in JavaScript? There are three main types of errors that can occur while compiling a JavaScript program: **syntax errors**, **runtime errors** ( also called **exceptions** ), and **logical errors**. When an exception occurs, an object representing the error is created and thrown. The JavaScript language defines seven types of built-in error objects. @@ -7748,7 +8211,7 @@ decodeURIComponent("%"); // URIError ↥ back to top -## Q 14.3. What are the various statements in error handling? +## Q. What are the various statements in error handling? Below are the list of statements used in an error handling, 1. **try:** This statement is used to test a block of code for errors @@ -7787,7 +8250,7 @@ errorHandling(); // Error: is not a number. ↥ back to top -## Q 14.4. How do you create a custom error class in JavaScript? +## Q. How do you create a custom error class in JavaScript? You can create a custom error class by extending the built-in `Error` class. This lets you define domain-specific errors with custom names and additional properties. @@ -7836,30 +8299,121 @@ try { ↥ back to top -## # 15. PROMISES - -
+## Q. What are general error handling strategies in JavaScript? -## Q 15.1. What is a promise? +Robust JavaScript applications use several strategies to handle errors gracefully: -A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it\'s not resolved (for example, network error). It will be in one of the 3 possible states: **fulfilled**, **rejected**, or **pending**. +**1. try / catch / finally** -**Syntax:** +The most fundamental mechanism. `finally` always runs, making it useful for cleanup. ```js -const promise = new Promise(function (resolve, reject) { - // promise description -}) +function fetchData(url) { + try { + // risky operation + const data = JSON.parse(url); + return data; + } catch (err) { + console.error('Parsing error:', err.message); + return null; + } finally { + console.log('fetchData completed'); + } +} ``` -**Example:** +**2. Fail fast — validate inputs early** + +Throw errors as soon as invalid state is detected rather than propagating bad data deep into the system. ```js -let promise = new Promise(function(resolve, reject) { - // the function is executed automatically when the promise is constructed +function divide(a, b) { + if (b === 0) throw new RangeError('Cannot divide by zero'); + return a / b; +} +``` - // after 1 second signal that the job is done with the result "done" - setTimeout(() => resolve("done"), 1000); +**3. Typed / custom errors for precise catching** + +Use `instanceof` to handle different error types differently instead of a single generic catch. + +```js +try { + processRequest(data); +} catch (err) { + if (err instanceof ValidationError) { + respond(400, err.message); + } else if (err instanceof NetworkError) { + respond(503, 'Service unavailable'); + } else { + respond(500, 'Internal error'); + throw err; // rethrow unknown errors + } +} +``` + +**4. Global error handlers** + +Catch unhandled errors and promise rejections at the top level. + +```js +// Unhandled synchronous errors +window.onerror = function(message, source, line, col, error) { + logToServer({ message, source, line, col, stack: error?.stack }); +}; + +// Unhandled promise rejections +window.addEventListener('unhandledrejection', (event) => { + logToServer({ reason: event.reason }); + event.preventDefault(); +}); +``` + +**5. Async error handling with async/await** + +Always wrap `await` calls in `try/catch` or use a helper that converts rejections to `[error, result]` tuples. + +```js +async function loadUser(id) { + try { + const res = await fetch(`/api/users/${id}`); + if (!res.ok) throw new NetworkError(`HTTP ${res.status}`, res.status); + return await res.json(); + } catch (err) { + console.error('loadUser failed:', err); + throw err; + } +} +``` + + + +## # 15. PROMISES + +
+ +## Q. What is a promise? + +A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it\'s not resolved (for example, network error). It will be in one of the 3 possible states: **fulfilled**, **rejected**, or **pending**. + +**Syntax:** + +```js +const promise = new Promise(function (resolve, reject) { + // promise description +}) +``` + +**Example:** + +```js +let promise = new Promise(function(resolve, reject) { + // the function is executed automatically when the promise is constructed + + // after 1 second signal that the job is done with the result "done" + setTimeout(() => resolve("done"), 1000); }); ``` @@ -7875,7 +8429,7 @@ Promises have three states: ↥ back to top -## Q 15.2. What is promise chaining? +## Q. What is promise chaining? The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. It allows you to chain on another then call which will run when the second promise is fulfilled. The `.catch()` can still be called to handle any errors that might occur along the way. @@ -7907,7 +8461,7 @@ In the above handlers, the result is passed to the chain of .then() handlers wit ↥ back to top -## Q 15.3. What is promise.all()? +## Q. What is promise.all()? `Promise.all` is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. @@ -7939,7 +8493,7 @@ Promise.all([promise1, promise2]) ↥ back to top -## Q 15.4. What is the purpose of race method in promise? +## Q. What is the purpose of race method in promise? `Promise.race()` method will return the promise instance which is firstly resolved or rejected. @@ -7961,11 +8515,30 @@ Promise.race([promise1, promise2]).then(function (value) { **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-promise-race-7k6zh0?file=/src/index.js)** +**Practical use — implementing a request timeout:** + +A common interview pattern (asked at Amazon/Google) is to add a timeout to any async operation using `Promise.race()`: + +```js +function withTimeout(promise, ms) { + const timeout = new Promise((_, reject) => + setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms) + ); + return Promise.race([promise, timeout]); +} + +// Usage +withTimeout(fetch('/api/data'), 5000) + .then(res => res.json()) + .then(data => console.log(data)) + .catch(err => console.error(err.message)); // "Timed out after 5000ms" if slow +``` + -## Q 15.5. What are the pros and cons of promises over callbacks? +## Q. What are the pros and cons of promises over callbacks? Below are the list of pros and cons of promises over callbacks, @@ -7987,7 +8560,7 @@ Below are the list of pros and cons of promises over callbacks, ↥ back to top -## Q 15.6. How does await and async works in es6? +## Q. How does await and async works in es6? The **async** and **await** keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. @@ -8016,7 +8589,7 @@ fetchMethod(); ↥ back to top -## Q 15.7. What is difference between fetch() and XMLHttpRequest() in JavaScript? +## Q. What is difference between fetch() and XMLHttpRequest() in JavaScript? **1. XMLHttpRequest:** @@ -8065,7 +8638,7 @@ fetch("https://jsonplaceholder.typicode.com/todos/1") ↥ back to top -## Q 15.8. Explain fetch() properties in JavaScript? +## Q. Explain fetch() properties in JavaScript? A `fetch()` function is available in the global window object. The fetch() function takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise, whether it is successful or not. If request is successful `.then()` function will receive Response object, if request fails then `.catch()` function will receive an error object @@ -8152,7 +8725,7 @@ fetch(userRequest) ↥ back to top -## Q 15.9. What is the difference between Promise and AJAX? +## Q. What is the difference between Promise and AJAX? A Promise is **an interface** for asynchronous operations. They keep track of when asynchronous operations complete and what their results are and let you coordinate that completion and those results (including error conditions) with other code or other asynchronous operations. They aren\'t actually asynchronous operations in themselves. @@ -8162,7 +8735,67 @@ An Ajax call is a specific asynchronous operation that can be used with with a t ↥ back to top -## Q 15.10. What is difference between async or defer keyword in JavaScript? +## Q. What is `AbortController` and how do you cancel a fetch request? + +`AbortController` is a browser API that allows you to cancel one or more `fetch` requests (or any operation that accepts a signal). + +**Basic usage:** + +```js +const controller = new AbortController(); +const signal = controller.signal; + +// Start the request, pass the signal +fetch('/api/data', { signal }) + .then(res => res.json()) + .then(data => console.log(data)) + .catch(err => { + if (err.name === 'AbortError') { + console.log('Fetch was cancelled'); + } else { + throw err; + } + }); + +// Cancel the request after 3 seconds +setTimeout(() => controller.abort(), 3000); +``` + +**Cancel on component unmount (React pattern):** + +```js +useEffect(() => { + const controller = new AbortController(); + + fetch('/api/user', { signal: controller.signal }) + .then(res => res.json()) + .then(setUser) + .catch(err => { + if (err.name !== 'AbortError') console.error(err); + }); + + return () => controller.abort(); // cleanup on unmount +}, []); +``` + +**Using `signal.aborted` and `signal.reason` (modern API):** + +```js +const controller = new AbortController(); + +controller.abort('User navigated away'); // pass a reason + +console.log(controller.signal.aborted); // true +console.log(controller.signal.reason); // 'User navigated away' +``` + +*Note: `AbortController` also works with `addEventListener`, streams, and any custom async operation that accepts `AbortSignal`.* + + + +## Q. What is difference between async or defer keyword in JavaScript? **1. async Attribute** @@ -8188,7 +8821,74 @@ Like an asynchronously loaded script, the file can be downloaded while the HTML ↥ back to top -## Q 15.11. What is request header in javascript? +## Q. What is CORS (Cross-Origin Resource Sharing) in JavaScript? + +**CORS** is a browser security mechanism that controls how web pages can request resources from a different origin (domain, protocol, or port) than the one that served the page. It uses HTTP headers to tell browsers whether a given web page is allowed to access resources from a different origin. + +**Why CORS exists:** + +The browser enforces the **Same-Origin Policy** by default, which blocks JavaScript from making cross-origin requests. CORS provides a controlled way to relax this restriction. + +**How CORS works:** + +1. **Simple requests** (GET, POST with plain-text content types) — the browser automatically sends an `Origin` header; the server responds with `Access-Control-Allow-Origin`. +2. **Preflight requests** — for complex methods (PUT, DELETE) or custom headers, the browser first sends an `OPTIONS` request to check permissions. + +**Server-side response headers:** + +| Header | Purpose | +|--------|---------| +| `Access-Control-Allow-Origin` | Specifies which origins are permitted (`*` or specific origin) | +| `Access-Control-Allow-Methods` | Permitted HTTP methods | +| `Access-Control-Allow-Headers` | Permitted request headers | +| `Access-Control-Allow-Credentials` | Whether cookies/auth can be included | +| `Access-Control-Max-Age` | How long preflight results can be cached | + +**Example — Fetch with CORS:** + +```js +// Client-side request to a different origin +fetch('https://api.example.com/data', { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', // send cookies cross-origin (requires server to set Allow-Credentials: true) +}) + .then(res => res.json()) + .then(data => console.log(data)) + .catch(err => console.error('CORS error:', err)); +``` + +**Example — Preflight request flow:** + +``` +// Browser sends preflight: +OPTIONS /api/data HTTP/1.1 +Origin: https://myapp.com +Access-Control-Request-Method: DELETE +Access-Control-Request-Headers: Authorization + +// Server responds: +HTTP/1.1 204 No Content +Access-Control-Allow-Origin: https://myapp.com +Access-Control-Allow-Methods: GET, POST, DELETE +Access-Control-Allow-Headers: Authorization +Access-Control-Max-Age: 86400 +``` + +**Common CORS errors:** + +* `No 'Access-Control-Allow-Origin' header is present` — server does not permit the request origin. +* `CORS policy: credential flag is 'true' but the 'Access-Control-Allow-Origin' is '*'` — wildcard origin cannot be used with `credentials: 'include'`. + +*Note: CORS is enforced by the browser. Server-to-server calls (Node.js, curl) are not subject to CORS.* + + + +## Q. What is request header in javascript? The `headers` read-only property of the `Request` interface contains the `Headers` object associated with the request. Syntax @@ -8218,7 +8918,112 @@ myContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg' ↥ back to top -## Q. 15.14. How to get responses of multiple api calls, when some API fails? +## Q. What is the event loop in JavaScript? + +JavaScript is **single-threaded** — it can execute only one task at a time. The **event loop** is the mechanism that allows JavaScript to perform non-blocking I/O operations (like network requests and timers) despite this single-thread constraint. + +**How it works:** + +``` +Call Stack Web APIs / Node APIs Callback Queue / Microtask Queue + │ │ │ + ▼ ▼ ▼ +Executes sync setTimeout, fetch, Queued callbacks waiting +code (LIFO) DOM events, etc. to enter the call stack +``` + +1. Synchronous code runs on the **call stack** first. +2. Async operations (e.g. `setTimeout`, `fetch`) are handed off to Web APIs. +3. When complete, their callbacks are pushed to a **queue**. +4. The event loop continuously checks: *"Is the call stack empty?"* — if yes, it dequeues the next callback and pushes it onto the stack. + +**Microtask queue vs. macro-task queue:** + +* **Microtasks** (Promises `.then`/`.catch`, `queueMicrotask`, `MutationObserver`) are processed **before** the next macro-task. +* **Macro-tasks** (setTimeout, setInterval, I/O) are processed one per event-loop tick. + +**Example:** + +```js +console.log('1'); + +setTimeout(() => console.log('2'), 0); // macro-task + +Promise.resolve().then(() => console.log('3')); // microtask + +console.log('4'); + +// Output order: 1, 4, 3, 2 +``` + +*Explanation:* `1` and `4` run synchronously. Then the microtask queue drains (`3`). Then the macro-task fires (`2`). + + + +## Q. What is garbage collection in JavaScript? + +**Garbage collection (GC)** is the automatic process by which JavaScript frees up memory occupied by objects that are no longer reachable (i.e., no references point to them). + +**1. Reference Counting algorithm (legacy)** + +Tracks how many references point to an object. When the count drops to zero, the memory is freed. + +```js +let a = { name: 'Alice' }; // ref count: 1 +let b = a; // ref count: 2 +a = null; // ref count: 1 +b = null; // ref count: 0 → eligible for GC +``` + +**Problem — circular references:** + +```js +function createCycle() { + let obj1 = {}; + let obj2 = {}; + obj1.ref = obj2; // obj1 → obj2 + obj2.ref = obj1; // obj2 → obj1 (cycle) + // ref count never reaches 0 — memory leak with pure reference counting +} +``` + +**2. Mark-and-Sweep algorithm (modern)** + +The modern approach used by all major engines (V8, SpiderMonkey): + +1. **Mark phase** — starting from GC roots (`window`, global scope, call-stack variables), traverse all reachable objects and mark them. +2. **Sweep phase** — free all unmarked (unreachable) objects. + +Circular references are handled correctly because the cycle is unreachable from the root after both `obj1` and `obj2` go out of scope. + +**Common causes of memory leaks in JavaScript:** + +| Cause | Example | +|-------|---------| +| Global variables | Accidentally using `x = 1` without `let/const/var` | +| Forgotten timers | `setInterval` never cleared | +| Detached DOM nodes | DOM element removed but reference kept in a closure | +| Closures retaining large objects | A closure captures a large array it no longer needs | +| Unreleased event listeners | `addEventListener` without a matching `removeEventListener` | + +```js +// Memory leak — timer retains reference to element +const btn = document.getElementById('myBtn'); +const timer = setInterval(() => { + btn.textContent = new Date().toLocaleTimeString(); +}, 1000); + +// Fix — clear the timer when done +clearInterval(timer); +``` + + + +## Q. How to get responses of multiple api calls, when some API fails? **Promise.allSettled():** @@ -8254,11 +9059,11 @@ Promise.allSettled(promises) ↥ back to top -## Q. 15.15. Explain the use of Promise.any()? +## Q. Explain the use of Promise.any()? The `Promise.any()` method is used to handle multiple promises simultaneously, and it resolves with the value of the first fulfilled promise.regardless of whether any of the other promises reject. If all of the promises reject, then `Promise.any()` rejects with an `AggregateError` object that contains an array of rejection reasons. -The `Promise.any()` method takes an iterable of Promises as an input, and returns a new Promise. Here's an example: +The `Promise.any()` method takes an iterable of Promises as an input, and returns a new Promise. Here\'s an example: ```javascript const promise1 = new Promise((resolve, reject) => setTimeout(reject, 1000, 'Promise 1 rejected')); @@ -8279,7 +9084,7 @@ Promise.any([promise1, promise2, promise3])
-## Q 16.1. What is the difference between ES6 Map and WeakMap? +## Q. What is the difference between ES6 Map and WeakMap? **Map:** @@ -8397,7 +9202,7 @@ weakSet.add(obj1); weakSet.add(obj2); weakSet.has(obj2); // true -delete obj2; // Don't take it literally - you can't delete objects like that. Use scope to execute this. +delete obj2; // Don\'t take it literally - you can\'t delete objects like that. Use scope to execute this. weakSet.has(obj2); // false, because you deleted obj2, so WeakSet releases it automatically weakSet.delete(obj1); // obj1 deleted from the set @@ -8417,7 +9222,7 @@ weakSet.add(2); // ERROR, no primitive value ↥ back to top -## Q 16.3. List down the collection of methods available on WeakSet? +## Q. List down the collection of methods available on WeakSet? Below are the list of methods available on WeakSet, @@ -8447,7 +9252,7 @@ weakSetObject.delete(secondObject); ↥ back to top -## Q 16.4. List down the collection of methods available on WeakMap? +## Q. List down the collection of methods available on WeakMap? Below are the list of methods available on WeakMap, @@ -8477,7 +9282,7 @@ weakMapObject.delete(secondObject); ↥ back to top -## Q 16.5. What is an Iterator? +## Q. What is an Iterator? An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a `.next()` method which returns an object with two properties: @@ -8512,11 +9317,142 @@ console.log(number.next()); // {value: 30, done: false} ↥ back to top +## Q. What are async iterators and the `for await...of` loop? + +An **async iterator** is an object that implements the async iteration protocol: its `Symbol.asyncIterator` method returns an object with a `next()` method that returns a **Promise** resolving to `{ value, done }`. The `for await...of` loop consumes async iterables, making it easy to process streams, paginated APIs, or any async sequence. + +**Custom async iterator:** + +```js +function asyncRange(start, end, delay = 500) { + return { + [Symbol.asyncIterator]() { + let current = start; + return { + next() { + return new Promise(resolve => { + setTimeout(() => { + if (current <= end) { + resolve({ value: current++, done: false }); + } else { + resolve({ value: undefined, done: true }); + } + }, delay); + }); + } + }; + } + }; +} + +// for await...of consumption +async function main() { + for await (const num of asyncRange(1, 5)) { + console.log(num); // 1, 2, 3, 4, 5 (each after 500 ms) + } +} +main(); +``` + +**Practical use — paginated API:** + +```js +async function* fetchPages(url) { + let page = 1; + while (true) { + const res = await fetch(`${url}?page=${page++}`); + const data = await res.json(); + if (!data.items.length) return; + yield data.items; + } +} + +async function processAll() { + for await (const items of fetchPages('/api/products')) { + items.forEach(item => console.log(item.name)); + } +} +``` + +**Key differences from regular iterators:** + +| | Synchronous Iterator | Async Iterator | +|--|----------------------|----------------| +| Protocol | `Symbol.iterator` | `Symbol.asyncIterator` | +| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` | +| Loop | `for...of` | `for await...of` | +| Use case | Arrays, strings, Maps | Streams, paginated APIs | + + + +## Q. What are `WeakRef` and `FinalizationRegistry` in JavaScript? + +Introduced in **ES2021**, `WeakRef` and `FinalizationRegistry` provide low-level access to the garbage collector — primarily for caches and resource management. + +**WeakRef:** + +A `WeakRef` holds a *weak reference* to an object, meaning it does not prevent the object from being garbage-collected. Use `.deref()` to access the object; it returns `undefined` if already collected. + +```js +let obj = { name: 'Cache entry' }; +const ref = new WeakRef(obj); + +console.log(ref.deref()?.name); // 'Cache entry' + +obj = null; // remove strong reference — obj may now be GC'd + +// Later (after GC runs): +console.log(ref.deref()); // undefined (if already collected) +``` + +**FinalizationRegistry:** + +Lets you register a callback to be called when a registered object is garbage-collected. + +```js +const registry = new FinalizationRegistry((heldValue) => { + console.log(`${heldValue} was garbage collected`); +}); + +let target = { data: '...' }; +registry.register(target, 'myObject'); + +target = null; // allows GC to collect it +// When collected: logs "myObject was garbage collected" +``` + +**Practical use — weak cache:** + +```js +const cache = new Map(); + +function getExpensiveData(key) { + const ref = cache.get(key); + const cached = ref?.deref(); + if (cached) return cached; + + const result = computeExpensiveResult(key); + cache.set(key, new WeakRef(result)); + return result; +} +``` + +**Important caveats:** + +* GC timing is non-deterministic — never rely on `FinalizationRegistry` for critical cleanup. +* `WeakRef` should be a last resort; prefer `WeakMap`/`WeakSet` for most weak-reference patterns. + + + ## # 17. MODULES
-## Q 17.1. What is modules in ES6? +## Q. What is modules in ES6? Making objects, functions, classes or variables available to the outside world is as simple as exporting them, and then importing them where needed in other files. @@ -8572,7 +9508,7 @@ export class Alligator { ↥ back to top -## Q 17.2. What is dynamic import in JavaScript? +## Q. What is dynamic import in JavaScript? Dynamic `import()` (ES2020) allows you to import a module **on demand** at runtime rather than statically at the top of a file. It returns a **Promise** that resolves to the module object, enabling lazy loading and code splitting. @@ -8627,7 +9563,7 @@ console.log(messages.default.greeting);
-## Q 18.1. Describe the Revealing Module Pattern in javascript? +## Q. Describe the Revealing Module Pattern in javascript? Revealing module pattern is a design pattern, which let you organise your javascript code in modules, and gives better code structure. It gives you power to create public/private variables/methods (using closure), and avoids polluting global scope @@ -8674,38 +9610,130 @@ myModule._privateMethod(); // TypeError: protected by the module closure ↥ back to top -## Q 18.2. How do you detect javascript disabled in the page? - -You can use `