0% found this document useful (0 votes)
73 views28 pages

200 Questions

The document contains 50 JavaScript and 50 React interview questions and answers, categorized into beginner, intermediate, and advanced levels. It covers fundamental concepts such as data types, functions, and state management in JavaScript, as well as component architecture, lifecycle methods, and hooks in React. Each question is followed by a concise answer, making it a useful resource for interview preparation.

Uploaded by

jaymahato10125
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)
73 views28 pages

200 Questions

The document contains 50 JavaScript and 50 React interview questions and answers, categorized into beginner, intermediate, and advanced levels. It covers fundamental concepts such as data types, functions, and state management in JavaScript, as well as component architecture, lifecycle methods, and hooks in React. Each question is followed by a concise answer, making it a useful resource for interview preparation.

Uploaded by

jaymahato10125
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/ 28

50 JavaScript Interview Questions and Answers

Beginner Level Questions (1-20)


1. What are the different data types in JavaScript? JavaScript has several primitive data
types: String, Number, BigInt, Boolean, Undefined, Null, and Symbol. It also has a
complex data type, Object, which includes arrays and functions.

2. What is the difference between `==` and `===`? The `==` operator performs type
coercion, meaning it converts the operands to the same type before comparison. The
`===` operator (strict equality) does not perform type coercion and returns true only if
both the value and type are the same.

3. What is hoisting in JavaScript? Hoisting is JavaScript’s default behavior of moving


declarations to the top of the current scope. Variables declared with `var` are hoisted
but not initialized, while `let` and `const` are hoisted but remain in a “temporal dead
zone” until declaration.

4. Explain the difference between `let`, `var`, and `const` keywords.


• `var` declarations are globally or functionally scoped, can be re-declared
and updated
• `let` declarations are block-scoped, can be updated but not re-declared
within the same scope
• `const` declarations are block-scoped and cannot be updated or re-
declared

5. What would be the result of `3 + 2 + "7"`? The result would be the string `"57"`. The
expression is evaluated from left to right: `3 + 2` equals `5`, then `5` is concatenated
with string `"7"` to produce `"57"`.

6. What is `null` vs `undefined`? `undefined` means a variable has been declared but
not assigned a value. `null` is an assignment value that represents no value or empty
value.
7. How do you concatenate two strings in JavaScript? You can concatenate strings using
the `+` operator: `let result = "Hello" + "World";` or using template literals: `let result =
`Hello ${name}`;`.

8. What is the purpose of the `typeof` operator? The `typeof` operator returns a string
indicating the type of the unevaluated operand. For example, `typeof "hello"` returns
`"string"`.

9. What is the purpose of the `isNaN` function? The `isNaN()` function determines
whether a value is NaN (Not a Number). It returns `true` if the value is NaN, otherwise
`false`.

10. What are template literals in JavaScript? Template literals are string literals
enclosed by backticks (`) that allow embedded expressions using `${expression}` syntax.
They support multi-line strings and string interpolation.

11. What is an array and how do you access its elements? Arrays are ordered
collections of elements. You access elements using bracket notation with an index: `arr`
for the first element.

12. What is the difference between `null` and `undefined`? `undefined` is a primitive
value automatically assigned to variables that have been declared but not initialized.
`null` is an assignment value that represents intentionally empty or no value.

13. What are the possible ways to create objects in JavaScript? You can create objects
using object literals `{}`, constructor functions, `Object.create()`, or ES6 classes.

14. What is JSON and its common operations? JSON (JavaScript Object Notation) is a
lightweight data interchange format. Common operations include `JSON.stringify()` to
convert objects to JSON strings and `JSON.parse()` to parse JSON strings back to objects.
15. What is the purpose of the array slice method? The `slice()` method returns a
shallow copy of a portion of an array into a new array object. It doesn’t modify the
original array.

16. What is the purpose of the array splice method? The `splice()` method changes the
contents of an array by removing or replacing existing elements and/or adding new
elements in place.

17. What is the difference between slice and splice? `slice()` returns a new array
without modifying the original, while `splice()` modifies the original array and returns an
array of removed elements.

18. What is a first-class function? JavaScript treats functions as first-class citizens,


meaning functions can be assigned to variables, passed as arguments, and returned
from other functions.

19. What is the purpose of the `let` keyword? The `let` keyword declares block-scoped
variables that can be reassigned but not redeclared within the same scope.

20. What is the difference between `let` and `var`? `let` is block-scoped while `var` is
function-scoped. `let` doesn’t allow redeclaration in the same scope, while `var` does.

Intermediate Level Questions (21-35)

21. What is a closure? A closure is a function that has access to variables from its outer
(enclosing) scope even after the outer function has returned. It gives you access to an
outer function’s scope from an inner function.

22. Explain `call`, `apply`, and `bind` methods.


• `call()` invokes a function with a given `this` value and arguments provided
individually
• `apply()` is similar to `call()` but accepts arguments as an array
• `bind()` returns a new function with a bound `this` value

23. What are Promises? A Promise is an object representing the eventual completion or
failure of an asynchronous operation. It can be in one of three states: pending, fulfilled,
or rejected.

24. What is the purpose of `async/await`? `async/await` is syntactic sugar built on top
of Promises that makes asynchronous code look and behave more like synchronous
code, improving readability and maintainability.

25. What is the event loop in JavaScript? The event loop is a mechanism that allows
JavaScript to perform non-blocking operations by offloading operations to the browser
or Node.js runtime and handling callbacks when they complete.

26. What is event bubbling and event capturing? Event bubbling is when an event starts
from the target element and bubbles up to the document. Event capturing is the reverse
- events start from the document and capture down to the target element.

27. What are higher-order functions? Higher-order functions are functions that take
other functions as arguments or return functions. Examples include `map()`, `filter()`,
and `reduce()`.

28. What is an IIFE (Immediately Invoked Function Expression)? An IIFE is a function


that is defined and executed immediately. It’s commonly used to create a private scope:
`(function() { ... })()`.

29. What is the purpose of the `map` method? The `map()` method creates a new array
populated with the results of calling a provided function on every element in the calling
array.
30. What is event delegation? Event delegation is a technique where you attach a single
event listener to a parent element to handle events for multiple child elements, taking
advantage of event bubbling.

31. What is the difference between `setTimeout` and `setInterval`? `setTimeout`


executes a function once after a specified delay, while `setInterval` repeatedly executes
a function at specified intervals.

32. What is the purpose of the `reduce` method? The `reduce()` method executes a
reducer function on each element of an array, resulting in a single output value.

33. What is functional programming? Functional programming is a programming


paradigm that treats computation as the evaluation of mathematical functions and
avoids changing state and mutable data.

34. What is NaN and its role? NaN stands for “Not a Number” and is returned when an
operation cannot produce a meaningful numeric result.

35. What are primitive data types in JavaScript? Primitive data types are basic data
types that are not objects and have no methods. They include undefined, null, boolean,
string, number, bigint, and symbol.

Advanced Level Questions (36-50)

36. What is the ‘Strict’ mode in JavaScript? Strict mode is a feature that places the
program in a “strict” operating context, preventing certain actions and throwing more
exceptions. It’s enabled using `"use strict";`.

37. How do you explain closures and when to use them? Closures are created when a
child function accesses variables from its parent function’s scope. They’re useful for data
privacy, creating function factories, and maintaining state.
38. What is currying in JavaScript? Currying is a technique where a function with
multiple arguments is transformed into a sequence of functions, each taking a single
argument.

39. What is a generator function? Generator functions are functions that can be exited
and later re-entered. They’re defined using `function*` syntax and use `yield` to pause
execution.

40. What are WeakMap and WeakSet? WeakMap and WeakSet are collections that
hold weak references to their keys/values, meaning they don’t prevent garbage
collection if there are no other references.

41. How does JavaScript handle memory management? JavaScript uses automatic
memory management through garbage collection, which automatically frees up
memory that’s no longer being used.

42. What is the difference between shallow and deep copying? Shallow copy creates a
new object but nested objects are still referenced. Deep copy creates a completely
independent copy of the object and all nested objects.

43. What is the observer pattern? The observer pattern defines a one-to-many
dependency between objects so that when one object changes state, all its dependents
are notified automatically.

44. What is the prototype chain? The prototype chain is a mechanism by which objects
can inherit properties and methods from other objects through the prototype property.

45. What is the difference between `call`, `apply`, and `bind`? All three methods set the
`this` value for a function, but `call` takes arguments individually, `apply` takes
arguments as an array, and `bind` returns a new function.
46. What is a unary function? A unary function is a function that accepts exactly one
argument.

47. What is a pure function? A pure function is a function that always returns the same
output for the same input and has no side effects.

48. What is the purpose of the `freeze` method? `Object.freeze()` freezes an object,
making it immutable - you cannot add, delete, or modify its properties.

49. What is the purpose of the double exclamation (`!!`)? The double exclamation (`!!`)
is used to convert any value to a boolean. It’s a shorthand for `Boolean(value)`.

50. What is the difference between `proto` and `prototype`? `__proto__` is the actual
object that is used in the lookup chain, while `prototype` is the object that is used to
build `__proto__` when you create an object with `new`.

50 React Interview Questions and Answers

Beginner Level Questions (1-20)

1. What is React? React is an open-source JavaScript library developed by Facebook for


building user interfaces, particularly single-page applications. It uses a component-based
architecture and efficiently updates the DOM using a Virtual DOM.

2. What is JSX? JSX stands for JavaScript XML. It’s a syntax extension that allows you to
write HTML-like code within JavaScript files. JSX needs to be transpiled into
`React.createElement()` calls.

3. What is the difference between functional and class components? Functional


components are JavaScript functions that return JSX, while class components are ES6
classes that extend `React.Component`. With hooks, functional components can now
manage state and lifecycle events.

4. What is the difference between state and props? Props are read-only inputs passed
from parent to child components. State is an object that holds data and determines how
the component renders and behaves, managed within the component itself.

5. What is the Virtual DOM? The Virtual DOM is a programming concept where a virtual
representation of the UI is kept in memory and synced with the real DOM. React uses it
to optimize updates by batching changes.

6. What are React Hooks? Hooks are functions that let you “hook into” React state and
lifecycle features from functional components. Common hooks include `useState` and
`useEffect`.

7. What is a Single Page Application (SPA)? A SPA is a web application that loads a single
HTML page and dynamically updates content as the user interacts with the app, without
requiring full page reloads.

8. What are controlled vs uncontrolled components? Controlled components have their


state controlled by React through props and callbacks. Uncontrolled components
manage their own state internally.

9. What is the purpose of the key attribute in React lists? Keys help React identify which
items have changed, are added, or removed. They should be given to elements inside
arrays to provide a stable identity.

10. What are React fragments? React fragments allow you to group multiple elements
without adding extra nodes to the DOM. They can be written as `<React.Fragment>` or
`<>`.
11. What are stateless and stateful components? Stateless components don’t manage
their own state and only receive props. Stateful components manage their own state
and can change over time.

12. What is the difference between React Node, Element, and Component?
• React Node: Anything that can be rendered (string, number, element,
array)
• React Element: Plain object describing what should appear on screen
• React Component: Function or class that returns React elements

13. What is the difference between React and React Native? React is for web
applications, while React Native is for mobile app development. React Native uses native
components instead of web components.

14. What are the advantages of React? React offers advantages like component
reusability, virtual DOM for performance, strong community support, one-way data
binding, and easy debugging.

15. What is the difference between real DOM and virtual DOM? Real DOM is the actual
representation of the UI, while Virtual DOM is a JavaScript representation of the real
DOM. Virtual DOM is faster to manipulate and allows React to optimize updates.

16. What are forms in React? Forms in React are handled through controlled
components where form data is handled by React state, or uncontrolled components
where form data is handled by the DOM.

17. What is the difference between createElement and cloneElement? `createElement`


creates new React elements, while `cloneElement` clones existing elements and allows
you to override props.

18. What is the purpose of render method? The render method returns the JSX that
describes what should appear on the screen. It’s called whenever the component’s state
or props change.
19. What is the significance of constructor in React? The constructor is called before the
component is mounted. It’s used to initialize state and bind event handlers.

20. What is the difference between state and props? State is internal to a component
and can be changed, while props are external inputs that are read-only.
Intermediate Level Questions (21-35)

21. What is React lifecycle and its methods? React lifecycle methods are hooks that
allow you to tap into different phases of a component’s existence: mounting, updating,
and unmounting. Key methods include `componentDidMount`, `componentDidUpdate`,
and `componentWillUnmount`.

22. Explain useState and useEffect hooks. `useState` adds state to functional
components, returning current state and a setter function. `useEffect` performs side
effects and can replace lifecycle methods like `componentDidMount` and
`componentDidUpdate`.

23. What is prop drilling? Prop drilling is passing props through multiple component
layers to reach a deeply nested component. It can be solved using Context API or state
management libraries.

24. What is the Context API? The Context API provides a way to pass data through the
component tree without manually passing props at every level. It’s useful for global data
like themes or user authentication.

25. What are Higher-Order Components (HOCs)? HOCs are functions that take a
component and return a new component with enhanced functionality. They’re used for
code reuse and cross-cutting concerns.

26. What is reconciliation in React? Reconciliation is the process by which React


updates the DOM. It compares the current component tree with the previous one and
determines the minimum changes needed.
27. What are React Portals? React Portals provide a way to render children into a DOM
node outside the parent component’s DOM hierarchy while maintaining the React
component tree relationship.

28. How does React Router handle navigation? React Router provides components like
`BrowserRouter`, `Route`, and `Link` to handle client-side routing in single-page
applications.

29. What is React Strict Mode? React Strict Mode is a development tool that helps
identify potential problems in an application by enabling additional checks and
warnings.

30. What is the difference between useEffect and componentDidMount? `useEffect` is a


hook for functional components that combines functionality of multiple lifecycle
methods, while `componentDidMount` is a lifecycle method for class components that
runs after initial render.

31. What is React.memo? `React.memo` is a higher-order component that memoizes


functional components, preventing unnecessary re-renders when props haven’t
changed.

32. What is the useCallback hook? `useCallback` returns a memoized callback function
that only changes if one of its dependencies has changed, helping optimize
performance.

33. What is the useMemo hook? `useMemo` memoizes expensive calculations and only
recalculates when dependencies change, improving performance.

34. What is the useReducer hook? `useReducer` is an alternative to `useState` for


managing complex state logic. It accepts a reducer function and returns current state
and dispatch function.
35. What is the useRef hook? `useRef` returns a mutable ref object whose `.current`
property is initialized to the passed argument. It’s commonly used to access DOM
elements directly.

Advanced Level Questions (36-50)

36. What is React Fiber? React Fiber is a reimplementation of React’s reconciliation


algorithm that enables incremental rendering, allowing React to pause and resume work
to avoid blocking the browser.

37. What are Error Boundaries? Error Boundaries are React components that catch
JavaScript errors anywhere in their child component tree, log those errors, and display a
fallback UI.

38. What is server-side rendering (SSR)? SSR is the process of rendering React
components on the server and sending the complete HTML to the client, improving
initial load time and SEO.

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


Controlled components have their form data handled by React state, while uncontrolled
components store form data in the DOM and use refs to access values.

40. What is lazy loading in React? Lazy loading is a technique to load components only
when they’re needed, reducing initial bundle size. It’s implemented using `React.lazy()`
and `Suspense`.

41. What is the useContext hook? `useContext` allows functional components to


consume context values without wrapping them in a Consumer component.

42. What is the useLayoutEffect hook? `useLayoutEffect` runs synchronously after all
DOM mutations but before the browser paints, useful for DOM measurements.
43. What are custom hooks? Custom hooks are JavaScript functions that use other
hooks and allow you to extract and reuse stateful logic between components.

44. What is the difference between React.Fragment and div wrapper? React.Fragment
doesn’t create an extra DOM node, while div wrapper adds an additional element to the
DOM tree.

45. What is the purpose of getDerivedStateFromProps? `getDerivedStateFromProps` is


a static lifecycle method that returns an object to update state based on props changes.

46. What is the difference between useState and useReducer? `useState` is simpler for
basic state management, while `useReducer` is better for complex state logic with
multiple sub-values or when next state depends on previous state.

47. What is React concurrent mode? Concurrent mode is a set of features that help
React apps stay responsive by rendering component trees without blocking the main
thread.

48. What is the purpose of React.StrictMode? React.StrictMode helps identify potential


problems in applications by enabling additional checks and warnings in development
mode.

49. What is the difference between React.PureComponent and React.Component?


`React.PureComponent` implements `shouldComponentUpdate` with a shallow prop
and state comparison, while `React.Component` doesn’t.

50. What is the useImperativeHandle hook? `useImperativeHandle` customizes the


instance value that is exposed when using ref, allowing you to control what gets
exposed to parent components.

50 Node.js Interview Questions and Answers


Beginner Level Questions (1-20)

1. What is Node.js? Node.js is an open-source, cross-platform JavaScript runtime


environment that executes JavaScript code outside of a web browser. It’s built on
Chrome’s V8 JavaScript engine and uses an event-driven, non-blocking I/O model.

2. What is the difference between Node.js and JavaScript? JavaScript is a programming


language, while Node.js is a runtime environment that allows JavaScript to run on the
server-side. Node.js provides additional APIs for file system, networking, and other
server-side operations.

3. Why is Node.js single-threaded? Node.js uses a single-threaded model with an event


loop for handling concurrency. While the main application thread is single-threaded,
Node.js uses multiple threads in the background for I/O operations through the libuv
library.

4. What is NPM? NPM (Node Package Manager) is the default package manager for
Node.js. It’s used for installing, managing, and sharing reusable code packages from the
npm registry.

5. What is package.json? The `package.json` file is a manifest file that contains


metadata about a Node.js project, including its name, version, dependencies, and
scripts.

6. What is callback hell? Callback hell refers to heavily nested callbacks that make code
difficult to read and maintain. It occurs when dealing with multiple asynchronous
operations that depend on each other.

7. What is the event loop in Node.js? The event loop is Node.js’s mechanism for
handling asynchronous operations. It continuously checks the message queue and
executes callbacks when asynchronous operations complete.
8. What is middleware in Node.js? Middleware refers to functions that have access to
the request object, response object, and the next middleware function in the
application’s request-response cycle.

9. What is the purpose of module.exports? `module.exports` is used to export


functions, objects, or values from a module so they can be used in other modules using
`require()`.

10. What is the difference between synchronous and asynchronous programming?


Synchronous programming executes code sequentially, blocking until each operation
completes. Asynchronous programming allows operations to run concurrently without
blocking the main thread.

11. What are the 5 built-in modules in Node.js? Common built-in modules include: `fs`
(file system), `http` (HTTP server/client), `path` (file path utilities), `os` (operating system
utilities), and `crypto` (cryptographic functionality).

12. What is the role of the Buffer class? Buffer class is used to handle raw binary data in
Node.js. It’s useful when dealing with file operations, network operations, or any binary
data manipulation.

13. What is REPL in Node.js? REPL stands for Read-Eval-Print-Loop. It’s an interactive
shell that allows you to execute Node.js commands and see results immediately.

14. What is the difference between `process.nextTick()` and `setImmediate()`?


`process.nextTick()` executes callbacks before the next iteration of the event loop, while
`setImmediate()` executes callbacks in the next iteration of the event loop.

15. What is an EventEmitter? EventEmitter is a class that allows objects to emit events
and register listeners for those events. It’s central to Node.js’s event-driven
architecture.
16. What is the control flow function? Control flow functions manage the execution
order of asynchronous operations, helping to avoid callback hell and ensuring proper
sequencing.

17. What is the difference between `fork()` and `spawn()`? `spawn()` launches a new
process with a given command, while `fork()` creates a new instance of the V8 engine
specifically for running Node.js modules.

18. What are the different types of HTTP requests? Common HTTP methods include
GET (retrieve data), POST (submit data), PUT (update data), DELETE (remove data),
PATCH (partial update), HEAD, and OPTIONS.

19. What is the purpose of NODE_ENV? NODE_ENV is an environment variable that


indicates whether the application is running in development, production, or other
environments, allowing for environment-specific configurations.

20. How do you handle errors in Node.js? Error handling in Node.js can be done using
try-catch blocks, error-first callbacks, promise rejection handlers, or error middleware in

Express.

Intermediate Level Questions (21-35)

21. What is event-driven programming? Event-driven programming is an approach


where the flow of program execution is determined by events such as user actions,
sensor outputs, or messages from other programs.

22. What is the difference between `setImmediate()` and `setTimeout()`? `setTimeout()`


schedules execution after a specified delay, while `setImmediate()` schedules execution
immediately after the current event loop iteration.
23. What are promises in Node.js? Promises are objects representing the eventual
completion or failure of asynchronous operations, providing a cleaner alternative to
callbacks.

24. How do you use async/await in Node.js? `async/await` is syntactic sugar for
promises that makes asynchronous code look more like synchronous code, improving
readability.

25. What are streams in Node.js? Streams are objects that handle reading or writing
data continuously. There are four types: Readable, Writable, Duplex, and Transform.

26. What is the purpose of the `createServer()` method? `createServer()` creates an


HTTP server instance that can listen for requests on a specified port and handle them
with callback functions.

27. What are commonly used libraries in Node.js? Popular libraries include Express
(web framework), Mongoose (MongoDB ODM), Lodash (utility library), Moment.js (date
manipulation), and Socket.io (real-time communication).

28. What is clustering in Node.js? Clustering allows you to create child processes that
share the same server port, taking advantage of multi-core systems to handle more
load.

29. How do you manage sessions in Node.js? Sessions can be managed using libraries
like `express-session` with various storage options like memory, databases, or Redis.

30. What are the types of streams in Node.js? The four types of streams are: Readable
(reading data), Writable (writing data), Duplex (both reading and writing), and
Transform (modifying data while reading/writing).
31. What is the purpose of the `crypto` module? The `crypto` module provides
cryptographic functionality including hash functions, HMAC, cipher, decipher, sign, and
verify functions.

32. How do you connect MongoDB to Node.js? You can connect MongoDB using the
native MongoDB driver or Mongoose ODM by creating a connection string and
establishing a connection.

33. What is the difference between `require()` and `import`? `require()` is CommonJS
module syntax (synchronous), while `import` is ES6 module syntax (asynchronous) that
supports static analysis.

34. What is the purpose of the `path` module? The `path` module provides utilities for
working with file and directory paths, including parsing, formatting, and resolving paths.

35. How do you handle file uploads in Node.js? File uploads can be handled using
middleware like `multer` with Express, which processes multipart/form-data and
provides access to uploaded files.

Advanced Level Questions (36-50)

36. What is a cluster in Node.js? A cluster allows you to create multiple worker
processes that share the same server port, enabling better utilization of multi-core
systems.

37. What are cluster methods in Node.js? Key cluster methods include `fork()` (create
child process), `isMaster` (check if master process), `isWorker` (check if worker process),
and `send()` (send messages between processes).

38. How do you implement rate limiting in Node.js? Rate limiting can be implemented
using middleware like `express-rate-limit` or custom solutions using Redis or in-memory
storage to track request counts.
39. What is the purpose of the `util` module? The `util` module provides utility
functions for debugging and working with Node.js internals, including `util.promisify()`
for converting callback-based functions to promises.

40. How do you debug Node.js applications? Node.js provides built-in debugging
capabilities using the `--inspect` flag, debugger statements, and tools like Chrome
DevTools or VS Code debugger.

41. What is the difference between `spawn()` and `exec()`? `spawn()` launches a new
process and returns a stream, while `exec()` executes a command and returns the
output as a buffer.

42. How do you implement authentication in Node.js? Authentication can be


implemented using strategies like JWT tokens, session-based authentication, OAuth, or
passport.js middleware.

43. What are worker threads in Node.js? Worker threads allow you to run JavaScript in
parallel threads, useful for CPU-intensive tasks without blocking the main event loop.

44. How do you implement caching in Node.js? Caching can be implemented using in-
memory solutions like Redis, Memcached, or built-in caching mechanisms with
appropriate TTL (Time To Live) settings.

45. What is the purpose of the `zlib` module? The `zlib` module provides compression
and decompression functionality using gzip, deflate, and brotli algorithms.

46. How do you handle database connections in Node.js? Database connections should
be managed using connection pooling, proper error handling, and connection lifecycle
management to prevent memory leaks.
47. What is the difference between `setImmediate()` and `process.nextTick()`?
`process.nextTick()` has higher priority and executes before `setImmediate()`.
`process.nextTick()` callbacks are processed before the event loop continues.

48. How do you implement logging in Node.js? Logging can be implemented using
libraries like Winston, Bunyan, or built-in `console` methods with appropriate log levels
and formatting.

49. What is the purpose of the `dns` module? The `dns` module provides DNS lookup
functionality, allowing you to resolve domain names to IP addresses and vice versa.

50. How do you handle memory management in Node.js? Memory management


involves monitoring memory usage, preventing memory leaks, using streams for large
data, and implementing proper garbage collection strategies.

50 Express.js Interview Questions and Answers

Beginner Level Questions (1-20)

1. What is Express.js? Express.js is a fast, unopinionated, and minimalist web


framework for Node.js. It simplifies building web applications and APIs by providing
features for routing, middleware, and handling HTTP requests and responses.

2. How does Express.js differ from Node.js? Node.js is the runtime environment that
executes JavaScript on the server, while Express.js is a framework built on top of Node.js
that provides additional features and abstractions for web development.

3. How do you create a basic Express server?


const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000);
4. What is the purpose of middleware in Express? Middleware functions sit between
the request and response cycle, processing requests, modifying data, or handling errors
before sending a response.

5. How do you handle routing in Express? Routing is handled using methods like
`app.get()`, `app.post()`, `app.put()`, `app.delete()`, etc. Each route takes a path and a
callback function.

6. What are the different HTTP methods supported by Express? Express supports GET,
POST, PUT, DELETE, PATCH, HEAD, and OPTIONS methods.

7. How do you serve static files in Express? Use the `express.static()` middleware:
`app.use(express.static('public'))` to serve files from the public directory.

8. What is the role of `app.listen()` in Express? `app.listen()` starts the server and makes
it listen on a specified port for incoming requests.

9. How do you install and set up Express? Run `npm init` to create a project, then `npm
install express` to install Express. Create your app.js file and configure routes.

10. What do `req` and `res` mean in Express route handlers? `req` (request) contains
information about the HTTP request, while `res` (response) is used to send back a
response to the client.

11. How do you define route parameters in Express? Use a colon to define parameters:
`app.get('/user/:id', (req, res) => { res.send(req.params.id); })`.

12. What is the use of `next()` in middleware? `next()` passes control to the next
middleware function in the stack. Without it, the request may hang.
13. How do you handle form data in Express? Use `express.urlencoded({ extended: true
})` middleware to parse form data from POST requests.

14. What is the difference between `app.get()` and `app.post()`? `app.get()` handles
GET requests (typically for fetching data), while `app.post()` handles POST requests
(typically for submitting data).

15. How do you handle 404 errors in Express? Add middleware at the end of your
routes:
app.use((req, res) => {
res.status(404).send('Page not found');
});

16. How do you parse JSON request bodies? Use the built-in `express.json()`
middleware: `app.use(express.json())`.

17. What is the purpose of `app.use()`? `app.use()` mounts middleware functions at a


specified path or globally for all routes.

18. How do you handle query parameters? Query parameters are accessed through
`req.query` object: `req.query.name` for `/users?name=john`.

19. What is route matching in Express? Express matches routes in the order they are
defined, using the first matching route and ignoring subsequent matches.

20. How do you create a simple “Hello World” Express application?


const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000, () => console.log('Server running on port 3000'));
Intermediate Level Questions (21-35)
21. What is the concept of middleware in Express? Middleware functions have access
to request and response objects and can modify them, end the request-response cycle,
or call the next middleware using `next()`.

22. How do you implement error handling in Express? Error-handling middleware


functions have four parameters `(err, req, res, next)` and should be defined at the end of
the middleware stack.

23. What are route parameters and how do you use them? Route parameters are
named URL segments that capture values. They’re accessed via `req.params`:
`/users/:id` captures the id parameter.

24. How do you implement file uploads in Express?


Use middleware like `multer` to handle multipart/form-data and file uploads: const
multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded');
});

25. What is CORS and how do you enable it? CORS (Cross-Origin Resource Sharing)
allows web pages to make requests to different domains. Enable it using the `cors`
middleware package.

26. How do you create and use custom middleware?


Define a function with `(req, res, next)` parameters and use `app.use()` to mount it:
function logTime(req, res, next) {
console.log(Date.now());
next();
}
app.use(logTime);
27. How do you organize routes using `express.Router()`? Create route modules using
`express.Router()` and mount them:

28. How do you handle environment variables? Use the `dotenv` package to load
environment variables from a `.env` file and access them via `process.env`.

29. What is the difference between `app.use()` and `app.get()`? `app.use()` mounts
middleware for all HTTP methods, while `app.get()` only handles GET requests.

30. How do you implement session management? Use `express-session` middleware to


manage user sessions:
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));

31. What is the purpose of the `body-parser` middleware? `body-parser` parses


incoming request bodies and makes the data available under `req.body`. It’s now built
into Express as `express.json()` and `express.urlencoded()`.

32. How do you implement authentication in Express? Authentication can be


implemented using strategies like JWT tokens, session-based auth, or libraries like
Passport.js.

33. What is the difference between middleware and route handlers? Middleware
functions run before route handlers and can modify request/response objects, while
route handlers specifically handle requests for certain routes.

34. How do you handle asynchronous operations in Express? Use async/await with
proper error handling or wrap async route handlers to catch errors:
app.get('/async', async (req, res, next) => {
try {
const data = await someAsyncOperation();
res.json(data);
} catch (error) {
next(error);
}
});

35. What are the different types of middleware in Express? Express has application-
level middleware, router-level middleware, error-handling middleware, built-in
middleware, and third-party middleware.
Advanced Level Questions (36-50)

36. How do you implement request validation? Use libraries like `express-validator` to
validate and sanitize input:
const { body, validationResult } = require('express-validator');
app.post('/user', body('email').isEmail(), (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Valid data');
});

37. How do you handle security in Express applications? Use middleware like `helmet`
for security headers, `cors` for CORS policy, rate limiting, input validation, and
authentication.

38. What are the pros and cons of using Express? Pros: Fast, minimal, large community,
flexible. Cons: Minimal structure, requires additional security measures, can become
complex with large applications.

39. How do you implement rate limiting? Use middleware like `express-rate-limit`:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);

40. How do you handle database connections in Express? Use connection pooling,
proper error handling, and connection lifecycle management. Close connections
properly and handle reconnection scenarios.

41. What is the difference between `res.send()` and `res.json()`? `res.send()` can send
various types of responses, while `res.json()` specifically sends JSON responses and sets
the appropriate Content-Type header.

42. How do you implement logging in Express? Use logging middleware like `morgan` or
custom logging solutions: const morgan = require('morgan');
app.use(morgan('combined'));

43. How do you handle file streaming in Express? Use Node.js streams with Express for
efficient file handling:
app.get('/download', (req, res) => {
const stream = fs.createReadStream('large-file.pdf');
stream.pipe(res);
});

44. What is the purpose of clustering in Express applications? Clustering allows you to
create multiple worker processes to handle more concurrent connections and take
advantage of multi-core systems.

45. How do you implement caching in Express? Implement caching using HTTP headers,
Redis, or memory caching: app.use('/api', (req, res, next) => {
res.set('Cache-Control', 'public, max-age=3600');
next();
});
46. How do you handle graceful shutdowns in Express? Listen for termination signals
and close server connections properly: process.on('SIGTERM', () => {
server.close(() => {
console.log('Server closed');
});
});

47. What is the difference between `app.param()` and route parameters? `app.param()`
is middleware that runs when a specific parameter is present in the route, while route
parameters are the actual values captured from the URL.

48. How do you implement WebSocket support in Express? Use libraries like `socket.io`
or `ws` alongside Express: const socketIo = require('socket.io');
const server = require('http').createServer(app);
const io = socketIo(server);

49. How do you handle content negotiation in Express? Use `res.format()` or check the
`Accept` header to serve different content types: app.get('/users', (req, res) => {
res.format({
'text/html': () => res.send('<h1>Users</h1>'),
'application/json': () => res.json(users)
});
});
app.get('/users', (req, res) => {
res.format({
'text/html': () => res.send('<h1>Users</h1>'),
'application/json': () => res.json(users)
});
});

50. How do you implement health checks in Express? Create dedicated endpoints for
health monitoring: app.get('/health', (req, res) => {
res.status(200).json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});

You might also like