Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Interview Notes :

Mern stack interview questions


https://www.youtube.com/watch?v=L-yrs6rARYo

Temporal Dead Zone


The state where variables are there in scope but not yet declared, like
console.log(a)
Let a = 3
Like this a is not declared error will come

we


𝐌𝐨𝐬𝐭𝐥𝐲 𝐚𝐬𝐤𝐞𝐝 𝐣𝐚𝐯𝐚𝐬𝐜𝐫𝐢𝐩𝐭 𝐢𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐪𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬


this keyword


Closures


Currying


setInterval & setTimeout


Event loop & Callback Queue


Flat & Filter nested objects/arrays


Higher order functions in JS?


Null vs Undefined


Cookies vs Session vs LocalStorage


Shallow Copy vs Deep Copy


Explain call, apply, and bind methods


Callback, Promise, async-await
Map and Set
Map vs filter

Continue with the mern stack interview question ?

Kafi sare react ke and mern stack ke interview questions dusre docs me hai

How can you optimise the project on react ?

See the axios also in react video , question can also be asked from that ?
Q. difference between null and undefined yeh sab
dekhlena thike ?

This was the question I was waiting for


Q. how the authentication is done ? how did you do it in your project when someone
is singing and login ?

Session storage:

Imagine it as a temporary storage that lasts only for the duration


of the current browsing session.
When you open a new tab or window in your browser, session
storage allows you to store data that can be accessed by different
pages within that session.
Once you close the browser or the session ends, the stored data
in session storage is automatically cleared and cannot be accessed
anymore.
Local storage:

Think of local storage as a long-term storage option that persists


even when you close the browser or restart your computer.
The data you store in local storage remains available until you
explicitly remove it or clear the browser's cache.
It allows you to store larger amounts of data compared to session
storage and can be accessed by different pages within the same
domain.

For an interview answer, you could say:

"Session storage and local storage are ways to store data in


JavaScript, but with some key differences. Session storage is like
a temporary storage that lasts only for the current browsing session,
while local storage is a long-term storage that persists even when
the browser is closed. Session storage is automatically cleared
when the session ends, while local storage remains available until
explicitly removed. Local storage allows storing more data and can
be accessed across different pages within the same domain."

DIfference betweeen get request and post request ?

To summarize, a GET request retrieves data from a server, while a


POST request sends data to a server to create or update
something.
In dono ka example dedena , jyada muskil nhi hai easy hai

Which one is more secure ? GET OR POST ?


a GET request, the parameters are often visible in the URL itself.
This can be problematic if sensitive information, such as passwords
or personal data, is included in the URL. URLs can be logged in
various places, including browser history, server logs, and proxy
servers.

Parameters in the request body: In a POST request, the parameters


are included in the request body instead of the URL, which offers
better security. The request body is not directly visible in browser
history or server logs.

Basic basic dsa in javascript dekh lena and react question bhi yahaper hai

Asynchronous operations

Starting line to give : asynchronous operations woh hote hai jo


independently execute hote hai normal flow se
Kyuki inko time lagta hai execute hone me , result ane me
They happen out of order .

An asynchronous operation in JavaScript refers to a type of operation that does not


block the execution of the program. Instead of waiting for the operation to complete
before moving on to the next task, JavaScript allows these operations to be executed
independently, enabling the program to continue running other tasks while waiting
for the asynchronous operation to finish.

CLOSURE
the inner function has access to the variables of the outer function's scope, even after the
outer function has finished executing. This is called closure.
*read more about this when you have time

IMPORTANT
what is async , await , promises , can you explain them
ChatGPT
Yes, I can explain async, await, and Promises in JavaScript.

Promises
A Promise is an object that represents the value of an asynchronous operation and tells us
whether it failed or is completed . Promises provide a way to handle asynchronous
operations and their results without blocking the main execution thread.

A Promise can be in one of three states:

● Pending: The initial state of a Promise. The Promise is neither fulfilled nor rejected.
● Fulfilled: meaning the asynchronous operation has completed successfully.
● Rejected: The Promise has been rejected with a reason, meaning the asynchronous
operation has failed.

Promises have two main methods for handling their eventual completion: then() and
catch(). The then() method is called when the Promise is fulfilled, and the catch()
method is called when the Promise is rejected. Both methods return new Promises, which
allow for chaining multiple asynchronous operations together.

Async/await
Async/awa ekit is a modern syntax for handling Promises in a more synchronous style.
async is a keyword used to define an asynchronous function, which always returns a
Promise. Within an async function, the await keyword can be used to pause the execution
of the function until a Promise is fulfilled or rejected.

Using async/await can make asynchronous code easier to read and understand,
especially when dealing with multiple Promises and their results. By using await, the code
can wait for the completion of a Promise before continuing execution, allowing for more
natural control flow.

Here is an example of how async/await can be used to handle asynchronous code:

js

async function myAsyanotherPromiseFunctionncFunction() {


try {
const result1 = await somePromiseFunction();
const result2 = await (result1);
const result3 = await yetAnotherPromiseFunction(result2);
return result3;
} catch (error) {
console.error(error);
return null;
}
}

In this example, the myAsyncFunction() is defined as an asynchronous function using the


async keyword. Inside the function, several Promises are called using the await keyword.
Each await statement pauses the execution of the function until the Promise is resolved or
rejected, at which point the result is returned and assigned to a variable.

The try...catch block is used to handle any errors that may occur during the execution
of the Promises. If any of the Promises are rejected, the execution of the function will
immediately jump to the catch block and any error will be caught and logged.

Overall, async/await can make writing and reading asynchronous code more intuitive and
easier to reason about.

but using await we have to wait for this promise to be completed then we will go to next one ,
so isnt it is the blocking the main execution thread
ChatGPT

While await will pause the execution of an async function until a Promise is resolved or
rejected, it does not block the main execution thread. When an async function is called, it
returns a Promise immediately, allowing other code to continue executing while the
asynchronous operation is running in the background.

When the await keyword is encountered inside an async function, the function's execution
is paused, but the main execution thread is not blocked. Instead, the JavaScript engine will
continue executing other code that is waiting to be processed, such as user input, event
handlers, and other asynchronous functions.

Once the Promise that is being awaited is fulfilled or rejected, the execution of the async
function resumes, and the function continues to run from where it left off. Any code that was
waiting for the completion of the Promise is now executed, and the results of the Promise
can be used in the function's logic.

So, using await does not block the main execution thread, but rather allows other code to
continue executing while waiting for the asynchronous operation to complete.

NOTE
When objects are compared they are compared using references , while the primitive
datatypes are compared using copy .

NOTE
All the keys inside the object are strings only under the hood

Cool question

Question 28:
const a = {};
const b = { key: 'b' };
const c = { key: 'c' };

a[b] = 123;
a[c] = 456;

console.log(a[b]);

Answer 456 Explanation Object keys are automatically converted into strings. We are
trying to set an object as a key to object a, with the value of 123.

However, when we stringify an object, it becomes "[object Object]". So what we are saying
here, is that a["[object Object]"] = 123. Then, we can try to do the same again. c is another
object that we are implicitly stringifying. So then, a["[object Object]"] = 456.

Then, we log a[b], which is actually a["[object Object]"]. We just set that to 456, so it returns
456.

Questions 29
let person = { name: 'Ayush' };
const members = [person];
person = null;

console.log(members);
In this code, we create an object called person and assign it a name property with a value
of 'Ayush'. Then, we create an array called members and assign it the value of [person].
At this point, the members array contains a reference to the person object.

Next, we set person to null, which means that the variable person no longer points to the
person object in memory. However, the members array still contains a reference to the
person object, which means that the object itself is not deleted from memory.

When we log the members array to the console, it shows the person object, which is still in
memory and accessible through the members array.

So, the output of the code is an array with one element, which is the person object: {
name: 'Ayush' }.

Q.

var obj = {a:1};


var secondObj = obj;
secondObj.a = 2;

console.log(obj);
console.log(secondObj);

var obj = {a:1};


var secondObj = obj;
secondObj = {a:2};

console.log(obj);
console.log(secondObj);

**Answer — 1. { a:2 }and { a:2 } 2. { a:1 }and { a:2 } Explanation — **1. If the object
property is changed, then the new object is pointing to the same memory address, so the
original object property will also change. ( call by reference ) 2. If the object is reassigned
with a new object then it is allocated to a new memory location, i.e it will be a real copy (call
by value).
Argument object
The number of arguments passed to a function we can get through them argument objects

Explain prototypal inheritance ?


Each object has its own private property which has link to another object called prototype
And that prototype has its own prototype and so on until its reached to null as a prototype
And if any prototype is created using reference then that prototype will have all its properties
and that is known as prototype inheritance

What do you mean by this in javascript ?

What is the value of this in global context ?


Ans : Global in node environment
And only window object in browser console

What is the difference between call() and apply() ?


Ans : Call takes number of arguments in comma separated fashion , while apply takes
number of arguments , while apply takes array of arguments

Q.What is currying ?
ADVANTAGE OF CURRYING
console.log(new Array(3).toString());

Answer “,,”** Explanation** Array.toString() creates string of the array with comma
separated values.
setTimeout interval

Interview quesions

https://www.youtube.com/watch?v=VlXZaO24DgY&t=279s

Make sure to read about this


for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}

for (let i = 0; i < 3; i++) {


setTimeout(() => console.log(i), 1);
}

MAM’s output based questions all in here


Here the output will be undefined bcaues by default end of line is determined by semicolon
,since you didnt write it wll behave like ;
Return ;
Second question

Q. important question here


let s = "sidahrth";
To check a palindrome first we need to make it to reversstring

s.split(‘’) -> will split each of them in the array ,


Then s.split(‘’).reverse() , will reverse the array and
s.split(‘’).reverse().join() will make it again in a string .

Q.

Best thing i get to learn is that +”23” ->> this will be converted into number
Even if there is +“ab” this is a uniary operator which will convert it into number and when
you try to print it won’t give a number it will says it is a NaN.

Q. console.log(1 + -”1” + “2”);


So here is - uniary operator , first that one will be converted to a integer 1 and then - will be
appended to it 1 -1 = 0 now
0+”2” that 0 will be converted to a string and will be appended to it
“02”

Q. type of NaN is a number ?


Yes can you try and run the code

Q. console.log("A"-"b"+"2");

Ans would Nan2, why because you can’t preform arithmetic operations on alphabet

Q. console.log(“A”-”B” + 2);

Ans , the answer would be NaN . because even if you try to add number to a NaN it would
result in NaN

Q . Note important questions


Doubt in this one

Reverse will make the changes in original array also same goes with even if you push into
arr2 , changes will be dynamic in nature .

Here in first case a1 and a2 are same , don’t think that a2 is a copy of a1 , they are same in
first case ,

Ok suppose you do this


NOTE
console.log(a1.slice());
So what it does that it will return the copy of that a1 .

Q. NOTE
And what if you do a1.slice(-1);

So it will return the last item of array

Q Some more important questions to be done ?


Ans
1 . console.log( 1 || 2)
2 . console.log( 1 || 0 )
3 . console.log(0 && 2)
4 . console.log( 1 && 2)
5 . console.log (2 && 4)

Ok lets discuss that


1
1
0
2
4
Why do these happens in last 2 , (1&&2) , here 1 is first check its truty , then next number , it
is also truthy and it return the second number .

Q.

What happens in this is that first it object then converted into number , and then type of
random is number , which is a number and its a truty value and and ! of it becomes false
and false !== string that is why else part will be running here

Q. next most important questions to be done


Here if you see your email is not updating why , because in the arrow functions does not
have this context , so this is here acting as a global object . and if you try to print this.email ,
it will global would created a email property

Q Note More important question to answer

Jab aap kisi object ko as a key daldte ho kisi aur ojbect toh woh stringify hoga “[object]
[object] ” aise baneg yeh
Toh aise kam hota hai iska
And then bus usko dekho apne aap samjh ajayega

NOTE Another Important question

Why this is even happening ?

See this you will get the approach and the answer that why it is coming like this
Isme hota kya hai ki jab call ka use karke immideiatly invoked hota hai yeh
Pearson hum as a object pass kar reh hai , toh this.name == persona.name ayega and
occupaton toh pass hi kardi thi apne

But next me kya hoga ek dam se chalta nhi hai woh apko funcitno ki refrence dega , and
apko usko explicity call karna padega
DIFFERENCE BETWEEN APPLY AND BIND AND CALL

apply(): The apply() method allows you to call a function with a given this value and an array
or an array-like object as the arguments. It takes two parameters: the first parameter is the
this value that will be used as the execution context inside the function, and the second
parameter is an array or an array-like object containing the arguments to be passed to the
function.

Here's an example usage of apply():

javascript
Copy code
function greet(name) {
console.log(`Hello, ${name}!`);
}

greet.apply(null, ['John']);
In this example, apply() is used to invoke the greet() function with 'John' as the argument.
Since apply() is called with null as the first parameter, the this value inside the greet()
function will be the global object (window in a browser environment).

bind(): The bind() method creates a new function with a specified this value and optional
arguments. It returns a new function that, when called, has its this value set to the provided
value, with a given sequence of arguments preceding any arguments provided when the
new function is called.

Here's an example usage of bind():


function greet(name) {
console.log(`Hello, ${name}!`);
}

const greetJohn = greet.bind(null, 'John');


greetJohn();

In this example, bind() is used to create a new function greetJohn that, when invoked, will
always pass 'John' as the argument to the greet() function. The null parameter passed to
bind() sets the this value inside the function to the global object.

The main difference between apply() and bind() is how they are used. apply() immediately
invokes the function with the provided arguments, while bind() returns a new function with
the specified this value and partially applied arguments, allowing you to call it later.

apply() takes the this value and an array of arguments.


bind() creates a new function with the this value and pre-defined
arguments.
call() takes the this value and individual arguments.

Aise
Ab yeh socho ki yeh aise kyu horha , tumne change arr2 wali index me kara but changes
arr1 me bhi kyu hogaya
When you assign arr2 to arr, arr2 simply points to the same array in memory as arr. So
when you modify arr2, you're actually modifying the same underlying array that arr points
to.

function foo(){
return (a) =>{
console.log(this.a);
};
}

var aa = {a:2};
var bb = {a:3};
var bar = foo.call(aa);
console.log(bar);
bar.call(bb);

Answer 2 kyu aya

Explanation :

1. We define a function foo, which returns an arrow function that logs the value of
this.a.
2. We create two objects, aa and bb, each with their own a property.
3. We call foo with aa as the this value using the call method, and assign the
returned arrow function to the variable bar.
4. We call bar with bb as the this value using the call method.

The output of the code will be 2, because when we call bar with bb as the this value, the
arrow function created by foo still refers to the a property of the aa object, due to the lexical
scoping rules of arrow functions.
In other words, this inside the arrow function refers to the this value of the surrounding
scope at the time the arrow function was created, which is the aa object in this case,
regardless of how the arrow function is called later on.

Q. What is dom ?

Ans : its just a structure of the webpage , it has different nodes and
different elements
it provides an interface for programs to access and manipulate the
content and structure of the page

Q. What is the difference between relative and absolute


position in css ?
Ans : "Relative positioning means an element is positioned relative to its
normal position on the page, while absolute positioning means it is
positioned relative to the position of nearest ancestor . When an element
is positioned absolutely, it's taken out of the normal flow of the page and
other elements may move to fill the space it was taking up."If there is no
positioned ancestor element, it will be positioned relative to the body of
the page.

Q. what is closure ?
Ans ; correct definition is written in the document only , you can try and read
,and example you can give is that you have a function and there are some
variables defined outside of the fucntion so the function can access those
functions which are outsfoe of the function and that is known as closure

Q. what are the new things introduced in es6 ?


Ans :let and const were introduced here , while earlier there was only var
And arrow functions and destructuring is also introduced here

Q. methods of an array ?
Ans : filter , map , foreach
Q. difference between map and foreach ?
Ans : map returns a value and foreach doesn’t return any value

REACT QUESTIONS START FROM HERE

Q. difference between functional components and class


components ?

Syntax
Functional components are just plain JavaScript functions that accept props
as an argument and return a React element.

Class components require you to extend from React.Component and create a


render function that returns a React element.

Extending from React.Component means that your class component


inherits from the React.Component class. This gives your class component
access to all of the methods and properties of the React.Component class.

State

Functional components can't have their own state. They can use the useState
hook to manage state, but this state is local to the function and not shared
with other instances of the component.

Class components can have their own state. This state is shared with all
instances of the component.

Lifecycle methods

Functional components don't have lifecycle methods. They can use the
useEffect hook to perform side effects, but this is not the same as lifecycle
methods.
Class components have lifecycle methods. These methods are called at
different points in the lifecycle of the component, such as when the component
is first created or when the component's props change.

In general, you should use functional components unless you have a specific
need for class components. Functional components are simpler, easier to
understand, and more performant. However, there are some cases where you
may need to use class components, such as if you need to use lifecycle
methods or if you need to have your own state that is shared with all instances
of the component.

Q. difference between usememo and usecallback ?


useMemo and useCallback are two hooks in React that help improve the
performance of functional components.

useMemo is used when you want to remember and reuse a calculated value.
It takes a function and an array of dependencies as input. The function is
executed, and the result is stored. The stored value is only recalculated if any
of the dependencies change. It's useful for expensive calculations or
operations that depend on certain values.
useCallback is used when you want to remember and reuse a function. It
takes a function and an array of dependencies as input. The function is
memoized, meaning it will only be recreated if any of the dependencies
change. It's useful when you want to pass a function to child components,
ensuring that the function reference remains the same and unnecessary
re-renders are avoided.
Q.how can we send data from child component back to
parent component ?
Ans : In React, components are designed to be modular and reusable. Often,
a parent component will contain one or more child components. In some
cases, it may be necessary for a child component to send data back up to its
parent component. For example, a form in a child component might collect
data that needs to be processed or saved in the parent component.

To enable this communication between a child component and its parent, we


can use a callback function that is passed down from the parent component to
the child component as a prop. This callback function is simply a function that
the parent component defines, which will be called by the child component
when it needs to send data up to the parent.

You can watch this video also

https://www.youtube.com/watch?v=NMerkZt7iVw&list=PLp18NAIKHWnvpLpio
Gs6ZAiMlpfx49KOz&index=17

I am going to watch only those videos from anshita jain which i need to for
interview preparation

Q. What is callback Function ?


Q. how to make application performance better ?
Improving application performance is a broad topic, but here are some general
tips that can help:

1. Optimize code: Make sure your code is optimized and not causing any
unnecessary delays. Use efficient algorithms and avoid unnecessary
looping or recursion. Avoid blocking operations and use asynchronous
operations whenever possible.
2. Reduce HTTP requests: Minimize the number of HTTP requests your
application makes. This can be achieved by combining CSS and
JavaScript files into a single file, compressing images, and using
content delivery networks (CDNs).
3. Implement caching: Caching can help improve performance by
reducing the amount of data that needs to be retrieved from the server.
Use browser caching, server caching, and CDN caching to improve
application performance.
4. Use lazy loading: Lazy loading is a technique that delays the loading of
non-critical content until it is needed. This can help reduce the initial
load time of your application and improve performance.
5. Optimize database queries: Make sure your database queries are
optimized and not causing any unnecessary delays. Use indexes, avoid
unnecessary joins, and minimize the number of queries needed.
6. Implement pagination: If your application displays a large amount of
data, consider implementing pagination to reduce the amount of data
that needs to be loaded at once.
7. Use a content delivery network (CDN): A CDN can help improve
performance by caching content and serving it from a server that is
closer to the user.

These are just a few general tips for improving application performance. There
are many other techniques and tools that can be used to improve
performance, depending on the specific needs and requirements of your
application.
Q. What are the different lifecycle methods in react ?

Imagine a component's life as a journey from being created to being


shown on the screen, and finally being removed. React provides these
lifecycle methods to perform specific tasks or actions at different points
of this journey.

state in React represents the current information or data that a component


holds. It's like a container inside a component where you can store and keep
track of values that can change over time.
Q. Differentiate between context api and react redux ?

Context API:

The Context API is a feature provided by React that allows you to share data
between components without passing props manually at each level.

It is primarily used for managing small to medium-sized applications with a few


levels of component nesting.

Context API provides a way to create a central data store (called a "context")
and components can access or update the data stored in that context.

It is built into React, so no additional libraries are required.

The Context API is simpler to set up and has less boilerplate code compared
to Redux.

However, it may have performance implications in larger applications or with


frequent updates to the shared data.

Redux:

Redux is a standalone state management library that can be used with React,
as well as other JavaScript frameworks or libraries.

It is particularly designed for managing complex application states, especially


in large-scale applications with deep component hierarchies.

Redux follows a specific pattern for managing state known as a "single source
of truth." This means that the entire application state is stored in a single
central location called the "store."

Redux promotes immutability, which means that the state is not directly
modified. Instead, new copies of the state are created for each update,
ensuring data integrity.

Redux enforces a unidirectional data flow, where actions are dispatched to


modify the state in a predictable way. These actions are handled by functions
called "reducers" that specify how the state should be updated.
Q. what are actions and reducers in react redux ?

In simpler terms, actions are like a message that describes something that
happened in the application, while reducers are like a handler that receives
the message and updates the application state accordingly.

Q. difference between state and props ?


https://www.youtube.com/watch?v=gvnlfNBb5us

In React, "state" refers to an object that holds data specific to a component. It


represents the current values of the component's data at a particular moment.

The useState hook is a React hook that allows you to manage state in
functional components. State is data that changes over time, and it is used to
keep track of the current state of your application

The useState hook takes two arguments: a default value for the state variable,
and a function that is used to update the state variable. The default value is
the value that the state variable will have when the component first renders.
The update function is used to change the value of the state variable
The useEffect hook is a React hook that allows you to perform side effects in
your functional components. Side effects are things like fetching data, making
API calls, or updating the DOM.

Javascript output based questions

Question 34:

const arrTest = [10, 20, 30, 40, 50][1, 3];

console.log(arrTest);

Answer 40** Explanation** The last element from the second array is used as
the index to get the value from first array like arrTest[3].

Q.

console.log([] + []); (1)

console.log([1] + []); (2)

console.log([1] + "abc"); (3)

console.log([1, 2, 3] + [1, 3, 4]); (4)

**Answer — **1. "" 2. "1" 3. "1abc" 2. "1,2,31,3,4" **Explanation — **1. An


empty array is while printing in console.log is treated as Array.toString(), so it
prints an empty string. 2. An empty array when printed in console.log is
treated as Array.toString() and so it is basically “1” + “” = "". 3. “1” + “abc” =
"1abc". 4.“1, 2, 3” + “1, 3, 4” = "1,2,31,3,4".
Question 36:

const ans1 = NaN === NaN;

const ans2 = Object.is(NaN, NaN);

console.log(ans1, ans2);

Answer false true Explanation NaN is a unique value so it fails in equality


check, but it is the same object so Object.is returns true.

Q.

var a = 3;

var b = {

a: 9,

b: ++a

};

console.log(a + b.a + ++b.b);

1. We start by declaring a variable a and assigning it a value of 3.


2. Then, we declare a variable b and assign it an object with two
properties:
○ Property a with a value of 9.
○ Property b with the result of ++a. The ++a is a prefix increment
operation, which increments the value of a by 1 and assigns the
new value to b. So, after this operation, a becomes 4 and b also
becomes 4.

Question 38:

const arr = [1, 2, undefined, NaN, null, false, true, "", 'abc', 3];

console.log(arr.filter(Boolean)); (1)

const arr = [1, 2, undefined, NaN, null, false, true, "", 'abc', 3];

console.log(arr.filter(!Boolean)); (2)

**Answer —

1. [1, 2, true, “abc”, 3].


2. **It will throw an error. **Explanation — **1. Array.filter() returns the
array which matches the condition. As we have passed Boolean it
returned all the truthy value.
3. As Array.filter() accepts a function, !Boolean returns false which is not a
function so it throws an error Uncaught TypeError: false is not a
function.
Question 39:

const person = {

name: 'Ayush Verma',

.25e2: 25

};

console.log(person[25]);

console.log(person[.25e2]);

console.log(person['.25e2']);

Answer 25 25 undefined** Explanation** While assign the key the object


evaluates the numerical expression so it becomes person[.25e2] = person[25].
Thus while accessing when we use 25 and .25e2 it returns the value but for
'.25e2' is undefined.

Question 43:

let obj = {
x: 2,

getX: function() {

setTimeout(() => console.log('a'), 0);

new Promise( res => res(1)).then(v => console.log(v));

setTimeout(() => console.log('b'), 0);

obj.getX();

Answer 1 a b** Explanation** When a macrotask is completed, all other


microtasks are executed in turn first, and then the next macrotask is executed.

Mircotasks include: MutationObserver, Promise.then() and Promise.catch(),


other techniques based on Promise such as the fetch API, V8 garbage
collection process, process.nextTick() in node environment.

Marcotasks include initial script, setTimeout, setInterval, setImmediate, I/O, UI


rendering.

An immediately resolved promise is processed faster than an immediate timer


because of the event loop priorities dequeuing jobs from the job queue (which
stores the fulfilled promises’ callbacks) over the tasks from the task queue
(which stores timed out setTimeout() callbacks).

Question 44:

const shape = {

radius: 10,

diameter() {
return this.radius * 2;

},

perimeter: () => 2 * Math.PI * this.radius,

};

console.log(shape.diameter());

console.log(shape.perimeter());

Answer 20 and NaN Explanation Note that the value of diameter is a regular
function, whereas the value of perimeter is an arrow function.

With arrow functions, the this keyword refers to its current surrounding scope,
unlike regular functions! This means that when we call perimeter, it doesn't
refer to the shape object, but to its surrounding scope (window for example).

There is no value radius on that object, which returns NaN

Question 46:

function Person(firstName, lastName) {

this.firstName = firstName;

this.lastName = lastName;

const ayush = new Person('Ayush', 'Verma');

const sarah = Person('Sarah', 'Smith');


console.log(ayush);

console.log(sarah);

Answer Person {firstName: "Ayush", lastName: "Verma"} and undefined


Explanation For sarah, we didn't use the new keyword. When using new, this
refers to the new empty object we create. However, if you don't add new, this
refers to the global object!

We said that this.firstName equals "Sarah" and this.lastName equals "Smith".


What we actually did, is defining global.firstName = 'Sarah' and
global.lastName = 'Smith'. sarah itself is left undefined, since we don't return a
value from the Person function.

*imp Q. what is the difference between the angular and react ?


Ans : angular is a complete MVC and react is only the view of MVC

React uses the virtual dom and angular uses the real dom

In angular you have 2 way data binding , you can pass from parent to child
and child to parent.

While is in react we have one way binding , passing data from parent to child
but we can send the data child to parent using callbacks

React was created by fb and while other was by google


Q. What are controlled uncontrolled components ?

Q.What are HOC ? and what can you do with HOC ?

Ans : HOC are higher order components and they can be used
used for many tasks like code reuse

Prop manipulation: HOCs can modify or pass additional props


to the wrapped component. This can be used to inject data,
configuration, or behavior into the component

So HOF are the functions which takes component as an


arguemnt and returns it by adding some new features and it
also use for state abstraction and manipulation

PROP MANIPULATION IN DETAIL


.Prop manipulation in Higher-Order Components (HOCs) refers
to the ability of an HOC to modify or add additional props to the
component it wraps.

To explain it simply, let's imagine you have a component that


needs some extra data or behavior to function properly. You
can create an HOC that wraps that component and injects the
necessary props.

For example, let's say you have a UserComponent that


displays user information. However, you also need to pass an
isAuthenticated prop to determine whether the user is
logged in or not. Instead of manually passing the
isAuthenticated prop every time you use the
UserComponent, you can create an HOC called withAuth:

jsx

function withAuth(WrappedComponent) {

const isAuthenticated = true; // Some logic


to determine authentication status

// Return a new component with the additional


prop

return function WithAuth(props) {

return <WrappedComponent
isAuthenticated={isAuthenticated} {...props}
/>;

};
}

In this example, the withAuth HOC adds the


isAuthenticated prop to the component it wraps
(WrappedComponent). It determines the authentication status
and passes it as a prop along with any other props received.

Now, when you use the UserComponent with the withAuth


HOC:

jsx

const UserWithAuth = withAuth(UserComponent);

// Usage in the render method

<UserWithAuth name="John" age={25} />;

The UserWithAuth component will automatically have the


isAuthenticated prop injected by the withAuth HOC. You
don't need to manually pass it each time you use the
component.

This way, prop manipulation in HOCs simplifies the process of


injecting additional props or modifying existing props for
components, promoting reusability and reducing repetitive
code.
State abstraation and state manipultion in detail

Here's an explanation of how HOCs can assist with state abstraction and
manipulation:

1. State Abstraction: With HOCs, you can encapsulate complex state


logic within the HOC itself. This means that the wrapped component
doesn't need to be concerned with the implementation details of the
state logic. The HOC manages the state internally and passes down the
necessary state values and state manipulation functions as props to the
wrapped component.
2. State Manipulation: HOCs enable you to provide state manipulation
functions to the wrapped component. These functions can be used to
modify the state managed by the HOC. For example, you can pass a
function that updates a specific state value or performs more complex
operations like fetching data, filtering, or sorting.
Q. What is flux in react ?

Ans :

so it is an architectural pattern which enforces uni


directional data flow.

IN INTERVIEW YOU COULD DO LIKE THIS

"Flux is an architectural pattern used in React applications


to manage data flow. It follows a unidirectional data flow,
which makes it easier to understand and maintain the
application's state. Flux consists of four main components:
actions, dispatcher, stores, and views (React components).
Actions represent user interactions or events, and they
trigger changes to the data. The dispatcher receives these
actions and dispatches them to the appropriate stores.
Stores contain the application's state and logic for handling
actions. Views (React components) subscribe to stores and
update their UI based on changes in the store's state. By
using Flux, we can maintain a clear and predictable flow of
data in React applications."
Q. What is switch keyword used in react router ?

Ans : The Switch component in React Router is like a


traffic cop for your routes. It examines each route inside its
child components and renders the first one that matches
the current URL. Once a match is found, it stops checking
the rest of the routes. This behavior is useful when you
want to render only one specific route, ensuring that
multiple routes don't match simultaneously.

Q. How is React routing different from conventional


routing ?
Ans : In conventional routing , http request is send to the
server and it takes some time to get the data back from
server but in react only history attribute is changed . user
thinks that he is navigating on different webpages but we
are only changing history attribute and there are no http
request required in this

Q . Why React is So popular ?


Ans 1. React uses the virtual dom , so whenever data
changes in ui it actually compares the data and only update
the part of ui which actually needs to be updated instead of
re-rendering the whole page which makes it quite
performant

It has one way binding , and it makes debugging really


easy

*reusable components
*it uses jsx which uses html and javascript together
Q. map and foreach me farak padh lena please
Yeh wala code bhi dekhlena ek bar

Q- print numbers from 1 to 5 on interval of every 1 seconds


Example- 1, then wait 1 sec, 2, then wait 1 sec and so on..

Sidharth :
for(let i = 1; i<=5; i++){
setTimeout(()=>{
clg(i);
},1000);
}

You might also like