Skip to content

Commit 1a0b596

Browse files
Merge pull request #34 from kishor82/update/javascript-basics
Update README.md
2 parents 01b29cf + f5da084 commit 1a0b596

File tree

1 file changed

+272
-7
lines changed

1 file changed

+272
-7
lines changed

README.md

Lines changed: 272 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -922,7 +922,28 @@ console.log(y); // 10
922922

923923
## Q 2.14. What is scope chain in javascript?
924924

925-
*ToDo*
925+
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.
926+
927+
**Example:**:
928+
929+
```js
930+
let globalVar = "I'm a global variable";
931+
932+
function outer() {
933+
let outerVar = "I'm an outer variable";
934+
935+
function inner() {
936+
let innerVar = "I'm an inner variable";
937+
console.log(innerVar); // "I'm an inner variable"
938+
console.log(outerVar); // "I'm an outer variable"
939+
console.log(globalVar); // "I'm a global variable"
940+
}
941+
942+
inner();
943+
}
944+
945+
outer();
946+
```
926947

927948
<div align="right">
928949
<b><a href="#table-of-contents">↥ back to top</a></b>
@@ -2637,7 +2658,27 @@ SyntaxError: Rest element must be last element
26372658

26382659
## Q 7.20. What is difference between [] and new Array()?
26392660

2640-
*ToDo*
2661+
`[]` and `new Array()` are two different ways of creating an array, but they are functionally equivalent.
2662+
2663+
The primary difference between them is in how they are created and in their behavior when used with certain methods.
2664+
2665+
`[]` 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:
2666+
2667+
```js
2668+
const myArray = []; // create a new empty array
2669+
```
2670+
2671+
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:
2672+
2673+
```js
2674+
const myArray = new Array(); // create a new empty array
2675+
const myOtherArray = new Array(3); // create a new array with a length of 3
2676+
const myThirdArray = new Array("a", "b", "c"); // create a new array with three elements
2677+
```
2678+
2679+
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.
2680+
2681+
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.
26412682

26422683
<div align="right">
26432684
<b><a href="#table-of-contents">↥ back to top</a></b>
@@ -4120,7 +4161,27 @@ try {
41204161

41214162
## Q 9.30. How function overloading works in JavaScript?
41224163

4123-
*ToDo*
4164+
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.
4165+
4166+
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.
4167+
4168+
**Example**
4169+
4170+
```js
4171+
function myFunction() {
4172+
if (arguments.length === 1) {
4173+
console.log("Hello " + arguments[0]);
4174+
} else if (arguments.length === 2) {
4175+
console.log("Hello " + arguments[0] + " and " + arguments[1]);
4176+
} else {
4177+
console.log("Hello world");
4178+
}
4179+
}
4180+
4181+
myFunction(); // output: "Hello world"
4182+
myFunction("Alice"); // output: "Hello Alice"
4183+
myFunction("Bob", "Charlie"); // output: "Hello Bob and Charlie"
4184+
```
41244185

41254186
<div align="right">
41264187
<b><a href="#table-of-contents">↥ back to top</a></b>
@@ -5857,7 +5918,56 @@ An array is an object so it has all the same capabilities of an object plus a bu
58575918

58585919
## Q 11.33. What is difference between `{}` vs `new Object()`?
58595920

5860-
*ToDo*
5921+
**1. Object Literal Syntax (`{}`):**
5922+
5923+
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.
5924+
5925+
**Syntax:**
5926+
5927+
```js
5928+
let myObj = {
5929+
prop1: value1,
5930+
prop2: value2,
5931+
prop3: value3
5932+
};
5933+
```
5934+
5935+
**Example:**
5936+
5937+
```js
5938+
let person = {
5939+
name: "John",
5940+
age: 30,
5941+
city: "New York"
5942+
};
5943+
```
5944+
5945+
**2. Object Constructor Syntax (`new Object()`):**
5946+
5947+
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.
5948+
5949+
**Syntax:**
5950+
5951+
```js
5952+
let myObj = new Object();
5953+
```
5954+
5955+
**Example:**
5956+
5957+
```js
5958+
let person = new Object();
5959+
person.name = "John";
5960+
person.age = 30;
5961+
person.city = "New York";
5962+
```
5963+
5964+
**Difference:**
5965+
5966+
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.
5967+
5968+
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.
5969+
5970+
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()`).
58615971

58625972
<div align="right">
58635973
<b><a href="#table-of-contents">↥ back to top</a></b>
@@ -7818,15 +7928,56 @@ The `XMLHTTPRequest()` object is an API which is used for fetching data from the
78187928
78197929
## Q. 15.14. How to get responses of multiple api calls, when some API fails?
78207930
7821-
*ToDo*
7931+
**Promise.allSettled():**
7932+
7933+
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.
7934+
7935+
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.
7936+
7937+
**Example:**
7938+
7939+
```js
7940+
const promises = [fetch('api1'), fetch('api2'), fetch('api3')];
7941+
7942+
Promise.allSettled(promises)
7943+
.then(results => {
7944+
const successfulResults = [];
7945+
const failedResults = [];
7946+
7947+
results.forEach(result => {
7948+
if (result.status === 'fulfilled') {
7949+
successfulResults.push(result.value);
7950+
} else {
7951+
failedResults.push(result.reason);
7952+
}
7953+
});
7954+
7955+
console.log('Successful API calls:', successfulResults);
7956+
console.log('Failed API calls:', failedResults);
7957+
})
7958+
.catch(error => console.log('Error:', error));
7959+
```
78227960
78237961
<div align="right">
78247962
<b><a href="#table-of-contents">↥ back to top</a></b>
78257963
</div>
78267964
78277965
## Q. 15.15. Explain the use of Promise.any()?
78287966
7829-
*ToDo*
7967+
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.
7968+
7969+
The `Promise.any()` method takes an iterable of Promises as an input, and returns a new Promise. Here's an example:
7970+
7971+
```javascript
7972+
const promise1 = new Promise((resolve, reject) => setTimeout(reject, 1000, 'Promise 1 rejected'));
7973+
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'Promise 2 resolved'));
7974+
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 1500, 'Promise 3 resolved'));
7975+
7976+
Promise.any([promise1, promise2, promise3])
7977+
.then((value) => console.log(value)) // 'Promise 2 resolved'
7978+
.catch((error) => console.error(error)); // AggregateError: All promises were rejected
7979+
```
7980+
*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.*
78307981
78317982
<div align="right">
78327983
<b><a href="#table-of-contents">↥ back to top</a></b>
@@ -9034,11 +9185,125 @@ Microsoft formerly developed its own proprietary browser engines - Trident and E
90349185
</div>
90359186
90369187
#### Q 18.22. What is a Polyfill?
9188+
9189+
**Polyfill**
9190+
9191+
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.
9192+
9193+
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.
9194+
9195+
**Example**
9196+
9197+
```js
9198+
// polyfill for the Object.values()
9199+
if (!Object.values) {
9200+
Object.values = function(obj) {
9201+
var values = [];
9202+
for (var key in obj) {
9203+
if (obj.hasOwnProperty(key)) {
9204+
values.push(obj[key]);
9205+
}
9206+
}
9207+
return values;
9208+
};
9209+
}
9210+
9211+
// Now you can use Object.values() even in older browsers that don't support it natively
9212+
const obj = { a: 1, b: 2, c: 3 };
9213+
const values = Object.values(obj);
9214+
9215+
console.log(values); // Output: [1, 2, 3]
9216+
```
9217+
9218+
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.
9219+
9220+
<div align="right">
9221+
<b><a href="#table-of-contents">↥ back to top</a></b>
9222+
</div>
9223+
9224+
90379225
#### Q 18.23. What is optional chaining in JavaScript?
9226+
9227+
**Optional chaining**
9228+
9229+
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.
9230+
9231+
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.
9232+
9233+
**Example**
9234+
9235+
```js
9236+
const obj = {
9237+
a: {
9238+
b: {
9239+
c: 123
9240+
}
9241+
}
9242+
};
9243+
9244+
// Without optional chaining
9245+
if (obj && obj.a && obj.a.b && obj.a.b.c) {
9246+
console.log(obj.a.b.c); // output: 123
9247+
}
9248+
9249+
// With optional chaining
9250+
console.log(obj?.a?.b?.c); // output: 123
9251+
9252+
// Optional chaining with method
9253+
console.log(obj?.a?.b?.c.toString()); // output: "123"
9254+
```
9255+
<div align="right">
9256+
<b><a href="#table-of-contents">↥ back to top</a></b>
9257+
</div>
9258+
90389259
#### Q 18.24. How could you make sure a const value is garbage collected?
9260+
9261+
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.
9262+
9263+
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.
9264+
9265+
9266+
Here are some best practices to follow when working with const variables:
9267+
9268+
1. Only use `const` when you know that the value should not be reassigned.
9269+
9270+
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.
9271+
9272+
3. Use `let` or `var` instead of `const` if you need to reassign the value.
9273+
9274+
4. To ensure that a const value is garbage collected, remove all references to it.
9275+
9276+
**Example**
9277+
9278+
```
9279+
const myObj = {name: 'John', age: 30};
9280+
9281+
// Use myObj...
9282+
9283+
// Remove all references to myObj
9284+
myObj = null;
9285+
```
9286+
9287+
In this example, setting `myObj` to `null` removes the only reference to the object, allowing it to be garbage collected.
9288+
9289+
<div align="right">
9290+
<b><a href="#table-of-contents">↥ back to top</a></b>
9291+
</div>
9292+
90399293
#### Q 18.25. How Garbage Collection works in JavaScript?
90409294
9041-
*ToDo*
9295+
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.
9296+
9297+
**Example**
9298+
9299+
```js
9300+
let a = { b: { c: { d: "Hello" } } };
9301+
let e = a.b.c;
9302+
a = null;
9303+
```
9304+
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.
9305+
9306+
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.
90429307
90439308
<div align="right">
90449309
<b><a href="#table-of-contents">↥ back to top</a></b>

0 commit comments

Comments
 (0)