0% found this document useful (0 votes)
3 views

JavaScript Interview Questions (1)

The document contains a comprehensive list of JavaScript and React.js interview questions, categorized into beginner, intermediate, and advanced levels. Each question is accompanied by a concise answer and explanation, covering essential concepts such as variable scoping, asynchronous programming, React components, and performance optimization techniques. This resource serves as a valuable guide for candidates preparing for technical interviews in JavaScript and React.js.

Uploaded by

uraut6044
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)
3 views

JavaScript Interview Questions (1)

The document contains a comprehensive list of JavaScript and React.js interview questions, categorized into beginner, intermediate, and advanced levels. Each question is accompanied by a concise answer and explanation, covering essential concepts such as variable scoping, asynchronous programming, React components, and performance optimization techniques. This resource serves as a valuable guide for candidates preparing for technical interviews in JavaScript and React.js.

Uploaded by

uraut6044
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/ 14

✅ JavaScript Interview Questions (15 Total)

🔹 Beginner Level (1–5)

1. What is the difference between var, let, and const?

Answer:

 var is function-scoped and can be redeclared.


 let is block-scoped and cannot be redeclared in the same scope.

 const is block-scoped and cannot be reassigned.

Explanation:
let and const were introduced in ES6 and help avoid scoping issues that occur with var.

2. What is hoisting in JavaScript?

Answer:
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their
scope before code execution.

Explanation:
Only declarations are hoisted, not initializations. For example, console.log(a); var a = 5; logs
undefined.

3. What are primitive and non-primitive data types?

Answer:
 Primitive: string, number, boolean, null, undefined, symbol, bigint

 Non-primitive: objects, arrays, functions

Explanation:
Primitive types are immutable, non-primitive types are mutable and passed by reference.

4. Difference between == and === in JavaScript?

Answer:

 == checks for value equality with type coercion.

 === checks for both value and type equality.

Explanation:
Always prefer === to avoid bugs caused by implicit type conversion.
5. What is a closure in JavaScript?
Answer:
A closure is a function that remembers variables from its outer scope even after that scope has
closed.

Explanation:
Closures are used for data encapsulation and creating private variables.

🔹 Intermediate Level (6–10)


6. What is the event loop in JavaScript?

Answer:
The event loop handles asynchronous callbacks by placing them in a queue and executing them after
the main thread is empty.

Explanation:
It enables non-blocking I/O by using the call stack and callback/task queues.

7. Explain the difference between call, apply, and bind.

Answer:

 call: invokes a function with a given this and arguments list.

 apply: same as call, but takes arguments as an array.

 bind: returns a new function with this bound, but doesn’t invoke it.

Explanation:
Useful in borrowing methods and setting context (this).

8. What is the difference between synchronous and asynchronous code?

Answer:

 Synchronous: executes line by line.

 Asynchronous: doesn’t block the code and uses callbacks, promises, or async/await.
Explanation:
Async code allows handling long operations like network requests without freezing the UI.

9. What is a higher-order function?

Answer:
A function that takes another function as an argument or returns a function.
Explanation:
Examples: map, filter, reduce. Enables functional programming.

10. What is the difference between shallow and deep copy?

Answer:
 Shallow copy: copies only the first level.

 Deep copy: copies all levels of the object.


Explanation:
Use structuredClone() or JSON.parse(JSON.stringify()) for deep copy (with limitations).

🔹 Advanced Level (11–15)

11. Explain prototypal inheritance.


Answer:
It’s a feature where objects can inherit properties and methods from another object.

Explanation:
Each object has a hidden [[Prototype]] or __proto__ pointing to another object.

12. What are Promises and how do you use async/await?

Answer:
Promises represent an eventual completion or failure of an async operation.
async/await is syntactic sugar for handling promises.

Explanation:
Use await inside async functions to pause execution until a promise settles.

13. What is debouncing and throttling?

Answer:

 Debouncing: Executes function after a delay once events stop.


 Throttling: Executes function at regular intervals regardless of events.

Explanation:
Used in performance optimization, e.g., search input or scroll handlers.

14. Explain memory leak and how to avoid it.

Answer:
A memory leak occurs when allocated memory is not released.
Explanation:
Avoid by clearing intervals/timeouts, detaching event listeners, and avoiding global variables.

15. What is the Temporal Dead Zone (TDZ)?

Answer:
The time between entering a block and initializing let/const variables.

Explanation:
Accessing them before declaration results in a ReferenceError.

✅ React.js Interview Questions (15 Total)

🔹 Beginner Level (1–5)

1. What is React?

Answer:
React is a JavaScript library for building user interfaces using a component-based architecture.
Explanation:
It uses virtual DOM and is maintained by Facebook.

2. What are components in React?

Answer:
Components are reusable UI blocks — they can be class-based or functional.

Explanation:
Functional components are now preferred, especially with hooks.

3. What is JSX?

Answer:
JSX stands for JavaScript XML. It allows writing HTML inside JavaScript.

Explanation:
Browsers can’t read JSX directly — it's compiled to React.createElement().

4. What is the use of key prop in lists?

Answer:
key helps React identify which items have changed, added, or removed.
Explanation:
Should be unique and stable for each element in a list.

5. What are props in React?

Answer:
Props are inputs to components used to pass data from parent to child.

Explanation:
They are read-only and help make components dynamic.

🔹 Intermediate Level (6–10)


6. What is state in React?

Answer:
State is a built-in object used to store component data that may change over time.
Explanation:
Use useState in functional components to manage state.

7. What is the difference between controlled and uncontrolled components?

Answer:

 Controlled: Form elements controlled by React via state.


 Uncontrolled: DOM handles its own state using refs.

Explanation:
Controlled components are preferred for predictable behavior.

8. What is lifting state up in React?


Answer:
Moving state to a common ancestor to share data between child components.

Explanation:
It promotes unidirectional data flow and avoids redundant state.

9. What are hooks in React?

Answer:
Hooks are functions that let you use React features like state and lifecycle in functional components.
Explanation:
Examples: useState, useEffect, useRef, useCallback, etc.
10. What does useEffect do?

Answer:
It performs side effects in functional components (like fetching data or updating the DOM).

Explanation:
It runs after render, and can be controlled with a dependency array.

🔹 Advanced Level (11–15)


11. What is memoization in React?

Answer:
React memoization (React.memo, useMemo, useCallback) optimizes performance by avoiding
unnecessary re-renders.

Explanation:
Useful in heavy computations and prop-driven re-renders.

12. Explain reconciliation and virtual DOM.

Answer:
Virtual DOM is a lightweight copy of the real DOM. React compares it to find and apply minimal
changes.

Explanation:
This diffing algorithm makes React fast and efficient.

13. What is Context API?

Answer:
Context provides a way to pass data through the component tree without props.
Explanation:
Use React.createContext() and useContext() to consume.

14. What is the difference between useEffect and useLayoutEffect?

Answer:

 useEffect: Runs asynchronously after DOM paint.

 useLayoutEffect: Runs synchronously after render but before the paint.

Explanation:
Use useLayoutEffect when DOM measurement is required before paint.
15. How does React handle re-renders?
Answer:
React re-renders when state or props change, and only the changed parts of the virtual DOM are
updated.

Explanation:
React compares the new virtual DOM with the old one to update efficiently.

Here are 15 more advanced and practical interview questions — 8 for JavaScript and 7 for React.js
— continuing from the previous list. These will deepen your understanding of real-world problem-
solving, architecture, and optimization topics.

✅ JavaScript Interview Questions (8 More)

1. What is the difference between .map(), .forEach(), .filter(), and .reduce()?


Answer:

 .map(): transforms each item and returns a new array.

 .forEach(): executes a function but returns undefined.

 .filter(): returns a new array of elements that match a condition.

 .reduce(): accumulates a single value based on the array.

Explanation:
Use .map() to transform, .filter() to select, .reduce() to aggregate, and .forEach() for side effects.

2. What is this in JavaScript and how does it behave in different contexts?


Answer:
this refers to the context in which a function is executed.

Explanation:

 Global scope → window (in browsers)

 Method → object that owns the method


 Arrow function → this is lexically bound

3. How do arrow functions differ from regular functions?

Answer:
Arrow functions:

 Don’t have their own this, arguments, super, or new.target.

 Cannot be used as constructors.


Explanation:
They are best used for short callbacks and avoid context binding issues.

4. What are JavaScript modules and why are they important?

Answer:
Modules allow code to be split into reusable pieces (import/export).

Explanation:
They improve maintainability, encapsulation, and make dependency management easier.

5. How does optional chaining (?.) work?


Answer:
It lets you access nested object properties safely without throwing an error if a value is null or
undefined.
const city = user?.address?.city;

Explanation:
Helps avoid deep null checks manually.

6. What is the difference between Object.freeze() and Object.seal()?

Answer:

 freeze(): makes an object immutable (can't add/remove/change properties).

 seal(): prevents adding/removing but allows modifying existing properties.

Explanation:
Used for object immutability control.

7. Explain the concept of event delegation.

Answer:
Event delegation is handling events at a parent element instead of each child using event bubbling.

Explanation:
Improves performance and dynamic DOM handling.

8. What is a generator function and where is it used?

Answer:
A generator (function*) returns an iterator and can pause/resume execution using yield.

function* idGen() {
let id = 0;
while (true) yield id++;

Explanation:
Useful for custom iterators, infinite sequences, and async flows.

✅ React.js Interview Questions (7 More)

1. What are custom hooks and why use them?

Answer:
Custom hooks are reusable functions that use React hooks to encapsulate logic.
Explanation:
They promote DRY code by abstracting logic (e.g., useForm, useFetch, useDebounce).

2. What is the purpose of useRef in React?

Answer:
useRef gives access to DOM elements or stores a mutable value that doesn’t trigger re-renders.

Explanation:
Used for timers, form elements, and persisting values between renders.

3. Explain React.StrictMode and what it does.

Answer:
It helps find potential problems in an application by activating extra checks and warnings during
development.

Explanation:
It double-invokes certain lifecycle methods to catch side effects and bugs early.

4. How do you optimize performance in a large React app?

Answer:

 Code splitting (React.lazy + Suspense)

 Memoization (React.memo, useMemo, useCallback)

 Virtualization (e.g., react-window)

 Avoid unnecessary state updates


 Debounce user input
Explanation:
Performance tuning is essential in large applications to avoid bottlenecks.

5. What is server-side rendering (SSR) in React?


Answer:
Rendering React components on the server before sending HTML to the client (e.g., Next.js).

Explanation:
Improves SEO and performance for initial page load.

6. What are the differences between React.memo, useMemo, and useCallback?

Answer:

 React.memo: memoizes entire component to avoid re-render.

 useMemo: memoizes a computed value.

 useCallback: memoizes a callback function.

Explanation:
They prevent unnecessary recalculations or renders.

7. What is the difference between rendering and reconciliation in React?

Answer:

 Rendering: creating React elements from components.


 Reconciliation: diffing new vs. old virtual DOM and applying changes to the real DOM.

Explanation:
Reconciliation optimizes DOM operations for efficient UI updates.

✅ React.js Interview Questions (Advanced - Set 3)

1. What is reconciliation in React and how does it work?


Answer:
Reconciliation is React’s process of comparing the new virtual DOM with the previous one and
determining the minimal set of changes to update the real DOM.
Explanation:
React uses a diffing algorithm (O(n)) to update only the changed parts, making UI updates efficient.
2. What are controlled and uncontrolled components in React?
Answer:

 Controlled: Form inputs where React state is the source of truth.

 Uncontrolled: Form inputs using refs to access DOM values.

Explanation:
Controlled components offer more control and validation; uncontrolled are simpler but less
predictable.

3. What is React.Fragment and when should you use it?

Answer:
<React.Fragment> lets you return multiple elements without adding extra nodes to the DOM.

<>

<h1>Hello</h1>

<p>World</p>

</>

Explanation:
Prevents unnecessary wrappers that can mess up styling and DOM structure.

4. What are synthetic events in React?

Answer:
Synthetic events are React's cross-browser wrapper around native events, providing a consistent API.

Explanation:
They improve compatibility across browsers while maintaining performance.

5. What are keys in React and why are they important?

Answer:
Keys help React identify which items have changed, added, or removed in lists.
items.map(item => <li key={item.id}>{item.name}</li>)

Explanation:
They enhance performance and prevent re-rendering the entire list.

6. What are Higher-Order Components (HOCs)?


Answer:
HOCs are functions that take a component and return a new enhanced component.
const withLogging = (Component) => (props) => {
console.log("Rendering");

return <Component {...props} />;

};

Explanation:
They’re used to share logic between components (e.g., auth, logging, data fetching).

7. What is the difference between useEffect(() => {}, []) and useLayoutEffect(() => {}, [])?

Answer:
 useEffect runs after paint.

 useLayoutEffect runs before paint, blocking the browser until the effect runs.

Explanation:
Use useLayoutEffect for DOM measurements or synchronously mutating layout.

8. How does React handle forms and form validation?

Answer:
React forms are typically managed using controlled components, with validation handled manually or
via libraries like Formik or React Hook Form.

Explanation:
Controlled forms provide full control over user input and validation logic.

9. What is the difference between props.children and React.cloneElement?

Answer:

 props.children accesses nested components or elements.


 React.cloneElement creates a new element by copying and modifying an existing one.

Explanation:
cloneElement is useful for injecting props or modifying children dynamically.

10. What are portals in React?


Answer:
Portals let you render children into a DOM node outside of the main app root.

ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'));

Explanation:
Used for modals, tooltips, and overlays where DOM positioning matters.
11. What is Context API and how is it used?

Answer:
Context provides a way to share global data like theme or auth without prop drilling.

const ThemeContext = React.createContext();


<ThemeContext.Provider value="dark">

<App />
</ThemeContext.Provider>

Explanation:
Use useContext() to access the value deeply in the component tree.

12. What are render props in React?


Answer:
A render prop is a technique for sharing code by passing a function as a prop to a component.

<DataProvider render={(data) => <List data={data} />} />

Explanation:
Allows components to be flexible with rendering logic.

13. Why is immutability important in React state management?

Answer:
React relies on detecting changes in state via reference comparison. Immutability ensures
predictable updates and efficient re-renders.
Explanation:
Avoid direct mutation (e.g., state.push()) and always return new objects/arrays.

14. What happens if you update state during rendering?

Answer:
React throws an error: Too many re-renders. React limits the number of renders to prevent an
infinite loop.

Explanation:
State updates must be in event handlers or lifecycle methods, not during render.

15. What are some popular performance optimizations in React apps?

Answer:
 Code splitting (React.lazy, Suspense)
 Memoization (React.memo, useMemo, useCallback)

 Virtualization (react-window)

 Avoiding inline functions/props

 Batching state updates

Explanation:
Performance tuning ensures smooth UX in complex apps with heavy DOM usage.

You might also like