JavaScript Interview Questions (1)
JavaScript Interview Questions (1)
Answer:
Explanation:
let and const were introduced in ES6 and help avoid scoping issues that occur with var.
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.
Answer:
Primitive: string, number, boolean, null, undefined, symbol, bigint
Explanation:
Primitive types are immutable, non-primitive types are mutable and passed by reference.
Answer:
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.
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.
Answer:
bind: returns a new function with this bound, but doesn’t invoke it.
Explanation:
Useful in borrowing methods and setting context (this).
Answer:
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.
Answer:
A function that takes another function as an argument or returns a function.
Explanation:
Examples: map, filter, reduce. Enables functional programming.
Answer:
Shallow copy: copies only the first level.
Explanation:
Each object has a hidden [[Prototype]] or __proto__ pointing to another object.
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.
Answer:
Explanation:
Used in performance optimization, e.g., search input or scroll handlers.
Answer:
A memory leak occurs when allocated memory is not released.
Explanation:
Avoid by clearing intervals/timeouts, detaching event listeners, and avoiding global variables.
Answer:
The time between entering a block and initializing let/const variables.
Explanation:
Accessing them before declaration results in a ReferenceError.
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.
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().
Answer:
key helps React identify which items have changed, added, or removed.
Explanation:
Should be unique and stable for each element in a list.
Answer:
Props are inputs to components used to pass data from parent to child.
Explanation:
They are read-only and help make components dynamic.
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.
Answer:
Explanation:
Controlled components are preferred for predictable behavior.
Explanation:
It promotes unidirectional data flow and avoids redundant state.
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.
Answer:
React memoization (React.memo, useMemo, useCallback) optimizes performance by avoiding
unnecessary re-renders.
Explanation:
Useful in heavy computations and prop-driven re-renders.
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.
Answer:
Context provides a way to pass data through the component tree without props.
Explanation:
Use React.createContext() and useContext() to consume.
Answer:
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.
Explanation:
Use .map() to transform, .filter() to select, .reduce() to aggregate, and .forEach() for side effects.
Explanation:
Answer:
Arrow functions:
Answer:
Modules allow code to be split into reusable pieces (import/export).
Explanation:
They improve maintainability, encapsulation, and make dependency management easier.
Explanation:
Helps avoid deep null checks manually.
Answer:
Explanation:
Used for object immutability control.
Answer:
Event delegation is handling events at a parent element instead of each child using event bubbling.
Explanation:
Improves performance and dynamic DOM handling.
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.
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).
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.
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.
Answer:
Explanation:
Improves SEO and performance for initial page load.
Answer:
Explanation:
They prevent unnecessary recalculations or renders.
Answer:
Explanation:
Reconciliation optimizes DOM operations for efficient UI updates.
Explanation:
Controlled components offer more control and validation; uncontrolled are simpler but less
predictable.
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.
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.
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.
};
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.
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.
Answer:
Explanation:
cloneElement is useful for injecting props or modifying children dynamically.
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.
<App />
</ThemeContext.Provider>
Explanation:
Use useContext() to access the value deeply in the component tree.
Explanation:
Allows components to be flexible with rendering logic.
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.
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.
Answer:
Code splitting (React.lazy, Suspense)
Memoization (React.memo, useMemo, useCallback)
Virtualization (react-window)
Explanation:
Performance tuning ensures smooth UX in complex apps with heavy DOM usage.