Professional Documents
Culture Documents
javascript interview questions
javascript interview questions
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
Kafi sare react ke and mern stack ke interview questions dusre docs me hai
See the axios also in react video , question can also be asked from that ?
Q. difference between null and undefined yeh sab
dekhlena thike ?
Session storage:
Basic basic dsa in javascript dekh lena and react question bhi yahaper hai
Asynchronous operations
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.
● 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.
js
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.
console.log(obj);
console.log(secondObj);
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
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
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("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
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 ,
Q. NOTE
And what if you do a1.slice(-1);
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
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
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.
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.
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.
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);
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 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. 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
Syntax
Functional components are just plain JavaScript functions that accept props
as an argument and return a React element.
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.
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.
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
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 ?
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.
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.
The Context API is simpler to set up and has less boilerplate code compared
to Redux.
Redux:
Redux is a standalone state management library that can be used with React,
as well as other JavaScript frameworks or libraries.
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.
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.
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.
Question 34:
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(ans1, ans2);
Q.
var a = 3;
var b = {
a: 9,
b: ++a
};
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 —
const person = {
.25e2: 25
};
console.log(person[25]);
console.log(person[.25e2]);
console.log(person['.25e2']);
Question 43:
let obj = {
x: 2,
getX: function() {
obj.getX();
Question 44:
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
};
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).
Question 46:
this.firstName = firstName;
this.lastName = lastName;
console.log(sarah);
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
Ans : HOC are higher order components and they can be used
used for many tasks like code reuse
jsx
function withAuth(WrappedComponent) {
return <WrappedComponent
isAuthenticated={isAuthenticated} {...props}
/>;
};
}
jsx
Here's an explanation of how HOCs can assist with state abstraction and
manipulation:
Ans :
*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
Sidharth :
for(let i = 1; i<=5; i++){
setTimeout(()=>{
clg(i);
},1000);
}