0% found this document useful (0 votes)
3K views18 pages

Faq JS 1

Uploaded by

maajinbuu132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views18 pages

Faq JS 1

Uploaded by

maajinbuu132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Javascript - FAQ SET 1

_________________________________________________
__

Q1 : How to catch errors through async?

Errors that occur during an asynchronous operation can be caught using a try-
catch block. Here is an example using async/await:

try {
let result = await asyncFunction();
} catch (error) {
// Handle the error here
}

You can also use the .catch() method to handle errors in promise-based
asynchronous code:

asyncFunction()
.then(result => {
// Do something with the result
})
.catch(error => {
// Handle the error here
});

It's important to note that you should always include a catch block, or use the
.catch() method, to handle any errors that may occur during an asynchronous
operation.

Q2 : Explain your understanding of synchronous and asynchronous


Javascript?

In JavaScript, synchronous code is executed in a blocking manner, meaning


that the script stops and waits for the current task to complete before moving
on to the next task. This type of execution is well-suited for small, simple tasks
that don't take a lot of time to complete.

On the other hand, asynchronous code is executed non-blocking, meaning that


the script does not stop and wait for a task to complete before moving on to
the next task. Instead, it continues to execute the next task, and when the
current task is completed, a callback function is called to handle the result.
This type of execution is well-suited for larger, more complex tasks that may
take a longer time to complete, as it allows the script to continue running
without blocking.

JavaScript uses a concurrency model based on an "event loop" which checks


the message queue for new messages, this way JavaScript can handle multiple
tasks at the same time and non-blocking the main thread.

JavaScript provides several ways to work with asynchronous code, such as


callbacks, promises, and async/await. Callbacks are a simple way to handle
asynchronous code, but they can quickly become difficult to manage and
understand as the codebase grows. Promises and async/await are more
modern and powerful ways to handle asynchronous code, they provide a more
readable and maintainable way of handling asynchronous operations.

Q3 : Explain about Callback Function?

In JavaScript, a callback function is a function that is passed as an argument


to another function and is executed after the outer function has completed its
execution. The callback function is typically used to perform some action or
process the result of the outer function's execution.

A callback function is simply a function that you pass as an argument to


another function. The outer function can then execute the callback function at
some later point. For example, here's a simple function that takes a callback
function as an argument:

function outerFunction(callback) {

// Do some work

callback();

You can then call the outer function and pass in a callback function like this:

outerFunction(function() {

console.log("Callback executed!");

});
This way you can use the callback function to execute a specific task after the
outer function has finished.
Callbacks are a common pattern in JavaScript, particularly when working with
asynchronous code. Many JavaScript APIs use callbacks to allow developers to
specify what should happen when an asynchronous operation completes. For
example, the setTimeout function takes a callback function as its first
argument, which is executed after the specified time interval has elapsed.
It's important to note that using callbacks can lead to callback hell, which is a
situation where multiple nested callbacks make the code hard to read and
maintain. Promises and async/await are more modern alternatives to
callbacks that provide a more readable and maintainable way of handling
asynchronous operations.

Q4 : Explain your understanding of promises?

In JavaScript, a promise is an object that represents the eventual completion


(or failure) of an asynchronous operation, and its resulting value. A promise is
in one of three states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation completed successfully.
rejected: meaning that the operation failed.
Promises are a more modern and powerful way to handle asynchronous
operations than callbacks. They provide a way to register callbacks for the
successful completion or failure of an asynchronous operation, and also
provide a way to compose multiple asynchronous operations together.
Promises have a then() method that allows you to attach callbacks for when
the promise is fulfilled, and a catch() method that allows you to attach
callbacks for when the promise is rejected. For example,

const myPromise = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("Hello, World!");
}, 1000);
});

myPromise.then((result) => {

console.log(result); // "Hello, World!"

});

Promises can also be chained together using the then() method, allowing you
to easily compose multiple asynchronous operations together. For example,
you can use then() to create a promise chain that performs multiple
asynchronous operations in sequence:
firstPromise()
.then(secondPromise)
.then(thirdPromise)
.catch(handleError);
Promises also have a static method called all() which allows you to wait for
multiple promises to be fulfilled before continuing.

Promise.all([promise1, promise2, promise3]).then((values) => {

console.log(values);

});
Promises are widely supported in modern JavaScript environments and
libraries, and are now a standard feature of the JavaScript language. They
provide a more readable and maintainable way of handling asynchronous
operations than callbacks.

Q5 : Explain about Async await?

Async/await is a more modern and powerful way to handle asynchronous


operations in JavaScript than callbacks or promises. It is built on top of
promises and allows you to write asynchronous code that looks and behaves
like synchronous code.
An async function is a function that is declared with the "async" keyword.
Async functions automatically return a promise, and you can use the "await"
keyword inside an async function to wait for a promise to be fulfilled.
Here is an example of how you can use async/await to handle an asynchronous
operation:
async function example() {

try {
const result = await asyncFunction();
console.log(result);
} catch (error) {
console.error(error);
}
}

The await keyword can only be used inside an async function, and it makes
JavaScript wait until that promise settles and returns its result.
You can also use async/await with Promise.all() to wait for multiple promises
to resolve.

async function process() {


const [result1, result2] = await Promise.all([promise1, promise2]);
console.log(result1, result2);

}
Async/await makes it easier to write and read asynchronous code and it's also
more readable and maintainable than using callbacks or chaining promises. It
also allows you to use try-catch blocks to handle errors, similar to synchronous
code.

Q6 : What is hoisting?

In JavaScript, hoisting is a behavior where variable and function declarations


are moved to the top of their scope. This means that variables and functions
can be used before they are declared in the code.
In JavaScript, variable declarations are hoisted to the top of their scope, but
their assignments are not. For example:
console.log(x); // undefined
var x = 5;

This code will output "undefined", not an error, because the variable
declaration "var x" is hoisted to the top of the scope, but the assignment "x =
5" is not.
On the other hand, function declarations are fully hoisted. This means that the
entire function, including its definition, is moved to the top of the scope. For
example:
example(); // Outputs "Hello, World!"
function example() {
console.log("Hello, World!");
}

This code will output "Hello, World!", because the function declaration is fully
hoisted to the top of the scope and can be called before it is defined in the
code.
It's important to note that variable initializations using let and const,
introduced in ECMAScript 6, are not hoisted like var. They are only accessible
within the block they are defined and not before they are defined.
In summary, hoisting is a behavior in JavaScript where variable and function
declarations are moved to the top of their scope, which allows them to be used
before they are declared in the code. However, variables declared with let and
const are not hoisted in the same way as var.

Q7 : Difference between let, var, const?

In JavaScript, var, let, and const are used to declare variables. The main
difference between these three keywords is the way they handle variable
scoping and reassignment.
var is the oldest way to declare variables in JavaScript, it is function scoped
which means that a variable declared with var inside a function is accessible
within the entire function, including nested functions. If a variable is declared
with var outside a function it becomes a global variable, accessible from
anywhere within your code. Variables declared with var can be re-declared and
re-assigned throughout the entire scope.
let and const were introduced in ECMAScript 6 (ES6) and they are block
scoped which means that a variable declared with let or const inside a block {}
is only accessible within that block. Variables declared with let can be re-
assigned throughout their entire scope, but cannot be redeclared, while
variables declared with const cannot be reassigned or redeclared after they
have been initialized.
In summary:
var is function scoped and can be re-declared and re-assigned throughout the
entire scope.
let is block scoped and can be re-assigned but not re-declared throughout the
entire scope.
const is block scoped and can be initialized only once and cannot be re-
assigned or re-declared.
It's worth noting that let and const are mostly used in modern javascript
development, as they provide more control over variable scoping and
reassignment than var.

Q8 : What is event Loop?

In JavaScript, the event loop is a mechanism that allows the execution of code
to be scheduled, so that a program can continue running while it waits for
other things to happen, such as user input, network responses, or timers to
expire. The event loop is what enables JavaScript to be a single-threaded
language that can still perform non-blocking I/O operations.
The event loop is a continuous process that constantly checks the message
queue for new messages(also called events) and processes them one by one in
the order they were added. Each message typically represents a task that needs
to be completed, such as a function call or an HTTP request.
The event loop has two main parts: the call stack and the message queue.
The call stack is a data structure that keeps track of the execution context of
the program. It stores the function calls that are currently being executed and
the order in which they were called.
The message queue is a data structure that stores the messages that need to be
processed. Each message has an associated callback function that will be
executed when it is processed.
When a function is called, it is added to the call stack and executed. If the
function contains asynchronous code, such as a setTimeout() or an
XMLHttpRequest, the browser will start a timer or initiate a network request.
Once the timer expires or the network request completes, the browser will add
a message to the message queue with the associated callback function to be
executed.
The event loop constantly checks the call stack and message queue. If the call
stack is empty, the event loop will take the first message from the message
queue and add its associated callback function to the call stack. This process
continues indefinitely, allowing the program to continue running and
responding to events even when it is waiting for asynchronous operations to
complete.
In summary, the event loop is a mechanism that allows JavaScript to execute
code in a non-blocking way by scheduling tasks and processing them
asynchronously through a continuous loop that checks the message queue for
new messages and adds them to the call stack to be executed.

Q9 : What is an object

In JavaScript, an object is a data type that represents a collection of properties


and methods. Properties are the values associated with an object, and methods
are the functions that an object can perform.
Objects are created using the object literal notation {} or the object constructor
function Object().
Here is an example of an object created using object literal notation:
const person = {
name: "John Doe",
age: 30,
occupation: "Developer",
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
}
};

Properties of an object can be accessed using dot notation


(objectName.propertyName) or bracket notation
(objectName["propertyName"])
console.log(person.name); // "John Doe"
console.log(person["age"]); // 30

Methods of an object can be invoked using dot notation or bracket notation


followed by parentheses.

person.sayHello(); // "Hello, my name is John Doe"

JavaScript objects are also known as "dynamic objects" because you can add,
modify, and remove properties and methods at any time after the object has
been created.
Objects in JavaScript are used to store and organize data, encapsulate
functionality, and represent real-world objects in your code. They are also
used to create complex data structures such as arrays and classes.
Q10 : What are classes in js?

In JavaScript, a class is a blueprint for creating objects (instances) with the


same properties and methods. Classes were introduced in ECMAScript 6 (ES6)
as a way to create objects using a more object-oriented programming (OOP)
approach.
A class is defined using the class keyword, followed by the name of the class,
and a pair of curly braces {} which contains the properties and methods of the
class. Here is an example of a simple class definition:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}

A class also has a special method called a constructor method, which is


automatically called when a new object is created from the class. The
constructor method is used to define and set the initial state of the object.
To create a new object from a class, you use the new keyword, followed by the
name of the class, and parentheses.

const person = new Person("John Doe", 30);

Once an object is created from a class, you can access its properties and
methods using dot notation (objectName.propertyName or
objectName.methodName()).

console.log(person.name); // "John Doe"


person.sayHello(); // "Hello, my name is John Doe"

Classes in JavaScript are a way to create objects using a more structured,


object-oriented approach. They provide a way to define a common structure
for multiple objects, and to encapsulate functionality and data in a single
place. They also provide a way to create objects with a common interface, and
to create new objects that inherit the properties and methods of a parent class.

Q10 : Do you Know about Closures?


Yes, In JavaScript, a closure is a function that has access to the variables and
functions in the scope where it was defined, even after the outer function has
returned. It "closes over" the variables and functions, preserving their state
and making them available for use later.
Here's an example of a closure:
function outerFunction(x) {
return function innerFunction() {
console.log(x);
};
}

const closure = outerFunction(5);


closure(); // logs "5"

In this example, the inner function "closes over" the variable x from the outer
function, preserving its state and making it available for use later, even after
the outer function has returned.
Closures are often used to create private variables and methods in JavaScript,
where a function is returned from another function, and the returned function
has access to the variables and functions in the outer function's scope, but the
outer function's variables and functions are not accessible from the outside.
Closures are also used in event handlers, callbacks, and other asynchronous
code to preserve the context of the function call and allow it to access variables
and functions from the surrounding scope.
Closures are an important concept in JavaScript and they allow you to create
powerful and expressive code. They can be used to create private variables and
methods, to preserve the context of a function call, and to create functions that
can be passed around and executed at a later time.

Q11 : Please tell the difference between using promise vs using async
await?

Promises and async/await are both ways to handle asynchronous operations in


JavaScript, but they are used in slightly different ways.
Promises are a way to handle asynchronous operations by returning an object
that represents the eventual completion (or failure) of an asynchronous
operation, and its resulting value. A promise has a then() method that allows
you to attach callbacks for when the promise is fulfilled, and a catch() method
that allows you to attach callbacks for when the promise is rejected.
For example, you can use a promise to handle an asynchronous operation like
this:

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("data fetched");
}, 1000);
});
}

fetchData()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
Async/await is a more recent way to handle asynchronous operations in
JavaScript. It is built on top of promises and allows you to write asynchronous
code that looks and behaves like synchronous code. An async function is a
function that is declared with the "async" keyword. Async functions
automatically return a promise, and you can use the "await" keyword inside an
async function to wait for a promise to be fulfilled.
Here is an example of how you can use async/await to handle an asynchronous
operation:

async function fetchData() {


try {
const data = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve("data fetched");
}, 1000);
});
console.log(data);
} catch (error) {
console.error(error);
}
}

Both promise and async/await are used to handle asynchronous operations,


but async/await provides a more readable and maintainable way of handling
asynchronous operations than callbacks or chaining promises. It also allows
you to use try-catch blocks to handle errors, similar to synchronous code.
In summary, Promises are a way to handle asynchronous operations by
returning an object that represents the eventual completion (or failure) of an
asynchronous operation, and its resulting value. While async/await is a more
recent way to handle asynchronous operations in JavaScript, it is built on top
of promises and allows you to write asynchronous code that looks and behaves
like synchronous code with readability

Q12 : explain null vs undefined?


In JavaScript, both null and undefined indicate the absence of a value, but
they are used in slightly different ways.
undefined is a built-in value that indicates that a variable has been declared
but has not been assigned a value. It is also the default value of function
parameters that are not provided when the function is called.
For example, the following code declares a variable x but does not assign it a
value, so it has the value undefined:
let x;
console.log(x); // undefined
null is a value that represents the intentional absence of any object value. It is
often used to indicate that a variable should have no value.
For example, the following code assigns the value null to the variable x:
let x = null;
console.log(x); // null
In summary, undefined indicates that a variable has been declared but has not
been assigned a value, while null is a value that represents the intentional
absence of any object value.
While using null variable is explicitly set to have no value, undefined is the
default value of variable when it's not defined or has no value assigned to it.
It's worth noting that null is an assignment value, while undefined is a default
value for variables that have not been assigned a value or for function
parameters that are not provided when the function is called.
In terms of comparison, null is considered to be an assignment value, while
undefined is considered as the default value for variables.
In addition, when checking for the existence of a variable or property, it is
generally recommended to use === null or !== null instead of == null or !=
null in order to make the distinction between null and undefined more clear.
In summary, undefined is a built-in value that indicates that a variable has
been declared but has not been assigned a value. null is a value that represents
the intentional absence of any object value, it is often used to indicate that a
variable should have no value. The main difference is that null is an
assignment value and undefined is a default value for variables that have not
been assigned a value or for function parameters that are not provided when
the function is called.

Q13 : What is a prototype?

In JavaScript, the prototype is an object that is associated with each function


and object. It is used to add properties and methods to an object, and to create
a hierarchical relationship between objects.
When an object is created, JavaScript automatically sets its prototype to be the
prototype of its constructor function. This allows the object to inherit
properties and methods from its prototype, and to share common
functionality with other objects that have the same prototype.
Each object has a __proto__ property that points to its prototype, and you
can use this property to access the prototype and its properties.
For example, you can create a Person constructor function, and then use it to
create two objects person1 and person2. Both of these objects will have the
same prototype, which is the prototype of the Person constructor function.
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person("John");


const person2 = new Person("Jane");
console.log(person1.__proto__ === person2.__proto__) // true

You can also add properties and methods to the prototype directly, and they
will be available to all objects that have that prototype.

Person.prototype.age = 30;
console.log(person1.age); // 30
console.log(person2.age); // 30

In summary, the prototype is an object that is associated with each function


and object in JavaScript. It is used to add properties and methods to an object,
and to create a hierarchical relationship between objects. Each object has a
__proto__ property that points to its prototype, and you can use this property
to access the prototype and its properties. The prototype is also the
mechanism that allows objects to inherit properties and methods from a
common ancestor.

Q14 : what is output of this code and explain.

var Employee = {
company: 'xyz'
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);

The output of this code will be "xyz".


This code creates an object Employee with a property company set to "xyz",
and then creates another object emp1 using the Object.create() method, which
sets the prototype of emp1 to be Employee. The delete operator is then used to
remove the company property from emp1.
However, since emp1 has Employee as its prototype, when trying to access the
company property on emp1, it will look for it on the prototype and find it
there, so it will return the value of company on Employee which is "xyz".
It's worth noting that when you use the delete operator on an object, it only
deletes the property from that object and not from the prototype. In this case,
the company property is deleted from emp1 but it still exists on Employee
object, so it can be accessed via prototype.

Q15 : what is output of this code and explain me


console.log(1);
setTimeout(()=> console.log(2), 0);
const myPromise = new Promise((resolve) => resolve())
myPromise.then(() => console.log(3));
console.log(4);

The output of this code will be:


1
4
3
2
This code has four statements:
The first statement console.log(1) is synchronous, it logs the value of 1
immediately.
The second statement setTimeout(()=> console.log(2), 0); creates a timer that
will run the callback function after 0 milliseconds (as soon as possible), but
the callback function is put in the task queue and it will be executed after the
execution stack is empty.
The third statement creates a new promise object and the promise is
immediately resolved and the then function is called, but the then function is
put in the task queue and it will be executed after the execution stack is empty.
The fourth statement console.log(4); is synchronous, it logs the value of 4
immediately.
After the execution stack is empty, the task queue is processed and the
callback of setTimeout and the then function of the promise are executed and
logged their respective values, the order of these two logged values may vary
based on the browser or environment.
In summary, JavaScript is single-threaded, and it processes each statement in
a synchronous manner, but the callbacks of setTimeout and the then function
of the promise are not executed immediately, they are put in the task queue
and executed only after the execution stack is empty.

Q16 : What is Ajax ?


Ajax (Asynchronous JavaScript and XML) is a set of technologies that allows a
web page to communicate with a server and update a part of the page without
refreshing the entire page. It is used to create dynamic and responsive web
applications that can update the content of the page without requiring a full
page reload.
The main technologies used in Ajax are JavaScript and XML, but today, most
developers use JSON (JavaScript Object Notation) instead of XML for data
exchange.
Ajax uses the XMLHttpRequest (XHR) object to exchange data with the
server. The XHR object allows JavaScript to make HTTP requests to the server
and receive responses without reloading the page.
Here is an example of how you can use the XHR object to make an HTTP GET
request to the server and update a part of the page with the response:

const xhr = new XMLHttpRequest();


xhr.open("GET", "https://example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
document.getElementById("content").innerHTML = data.content;
}
};
xhr.send();

In this example, the JavaScript code makes an HTTP GET request to


"https://example.com/data" and updates the content of the element with the
id "content" with the data received from the server.
Ajax can also be used with more advanced libraries and frameworks such as
jQuery, AngularJS, ReactJS and VueJS, which provide a higher-level
abstraction for making ajax requests and handling the response.
In summary, Ajax (Asynchronous JavaScript and XML) is a set of technologies
that allows a web page to communicate with a server and update a part of the
page without refreshing the entire page, it uses the XMLHttpRequest (XHR)
object to exchange data with the server, it makes it possible to create dynamic
and responsive web applications, it's widely used in modern web development.

Q17 : Difference between find and filter method?

In JavaScript, the find() and filter() methods are both used to iterate through
an array and retrieve specific elements, but they work in slightly different
ways.
The find() method returns the first element in an array that satisfies a given
condition. It takes a callback function as an argument, which is called for each
element in the array, and returns the first element for which the callback
function returns true.
Here's an example of how you can use the find() method to find the first
element in an array that is greater than 10:

const numbers = [1, 2, 3, 4, 5, 11, 12, 13];


const firstLargeNumber = numbers.find(number => number > 10);
console.log(firstLargeNumber); // 11

The filter() method, on the other hand, returns an array of all the elements in
the original array that satisfy a given condition. It also takes a callback
function as an argument, which is called for each element in the array, and
returns an array of all the elements for which the callback function returns
true.
Here's an example of how you can use the filter() method to find all elements
in an array that are greater than 10:

const numbers = [1, 2, 3, 4, 5, 11, 12, 13];


const largeNumbers = numbers.filter(number => number > 10);
console.log(largeNumbers); // [11, 12, 13]

In summary, The find() method is used to find the first element that satisfies a
given condition, while filter() method is used to find all elements that satisfy a
given condition and return them as an array.

Q18 : how to find any key in array of objects

To find a specific key in an array of objects, you can use the filter() method in
combination with the Object.keys() method. The Object.keys() method returns
an array of a given object's own enumerable property names, which can be
used to check if a specific key exists in the object.
Here's an example of how you can use the filter() method to find all objects in
an array that have a specific key:

const arrayOfObjects = [
{name: 'John', age: 30, city: 'New York'},
{name: 'Jane', age: 25, city: 'Los Angeles'},
{name: 'Mike', age: 35, city: 'Chicago'},
{name: 'Emily', age: 28}
];

const filteredObjects = arrayOfObjects.filter(object =>


Object.keys(object).includes('city'));
console.log(filteredObjects);

In this example, the filter() method is used to iterate through the


arrayOfObjects and for each object, Object.keys(object) is used to get an array
of all the object's own enumerable property names, the includes('city') is then
used to check if the array of keys includes the key 'city' and if yes, the object is
included in the filtered array.
You can also use some() method in place of includes() like this:

const filteredObjects = arrayOfObjects.filter(object =>


Object.keys(object).some(k => k === 'city'));

In summary, to find a specific key in an array of objects, you can use the
filter() method in combination with the Object.keys() method to iterate
through the array, for each object check if the array of keys returned by
Object.keys(object) includes the specific key you're looking for and if it does,
include that object in the filtered array.

Q19 : Why is javascript a single threaded language?

JavaScript is a single-threaded language because it can only process one task


at a time. This means that it can only execute one line of code at a time, and it
does this in a linear, sequential manner.
There are several reasons why JavaScript is single-threaded:
1. JavaScript was originally designed to be a simple scripting language for
web browsers. At the time, web browsers were not capable of running
multiple threads, so JavaScript was designed to work within this
limitation.
2. Single-threaded execution simplifies the programming model and
makes it easier for developers to reason about their code. When code
runs in a single thread, it is guaranteed to execute in a predictable order,
and it is less likely to encounter race conditions or other concurrency-
related issues.
3. JavaScript's single-threaded nature makes it easier to work with the
Document Object Model (DOM), which is the interface used to
manipulate web pages. Because the DOM is also single-threaded,
JavaScript can interact with it without the need for complex thread
synchronization mechanisms.
4. JavaScript's event-driven model is based on the idea of an event loop,
which is a mechanism that handles the execution of code in response to
events such as user input, network requests, and timers. Because the
event loop is single-threaded, it can handle multiple events and execute
their corresponding code in a predictable order.
To summarize, JavaScript is single-threaded because it was designed to work
within the limitations of web browsers at the time, it simplifies the
programming model and makes it easier for developers to reason about their
code, it makes it easier to work with the DOM and enables the event-driven
model that is based on the idea of an event loop.
Q20 : Explain about when you'll use call, bind and apply?

In JavaScript, the call(), bind() and apply() methods are used to change the
context of a function, also known as "binding" the function to a specific
context.
The call() method invokes a function with a given context and arguments
passed in individually. The first argument passed to the call() method is the
context that the function should be invoked with, and the remaining
arguments are passed as individual arguments to the function.
Here's an example of how you can use the call() method to change the context
of a function:

const person = { name: "John" };

function sayName() {
console.log(`My name is ${this.name}`);
}

sayName.call(person); // My name is John

The apply() method is similar to the call() method, but it takes the context and
arguments as an array. It invokes a function with a given context and
arguments passed in as an array.
Here's an example of how you can use the apply() method to change the
context of a function:

const person = { name: "John" };

function sayName(surname) {
console.log(`My name is ${this.name} ${surname}`);
}

sayName.apply(person, ["Smith"]); // My name is John Smith

The bind() method creates a new function with the same body and scope as the
original function, but with the context set to the first argument passed to
bind().
Here's an example of how you can use the bind() method to change the context
of a function:

const person = { name: "John" };

function sayName() {

console.log(My name is ${this.name});


}
const boundSayName = sayName.bind(person);
boundSayName(); // My name is John

In this example, the `bind()` method creates a new function


`boundSayName` with the same body and scope as the original `sayName`
function, but with the context set to the `person` object. When the
`boundSayName` function is invoked, it will have the context of `person` and
will log "My name is John".

In summary, `call()` method allows you to invoke a function with a given


context and arguments passed in individually, while `apply()` method is
similar to call but it takes the context and arguments as an array, whereas
`bind()` method creates a new function with the same body and scope as the
original function, but with the context set to the first argument passed to
`bind()`.

You would use `call()` or `apply()` when you want to invoke a function and
immediately change its context, whereas `bind()` is useful when you want to
create a new function with a specific context that can be invoked later.

You might also like