200 Questions
200 Questions
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.
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.
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.
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.
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()`.
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.
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.
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.
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`.
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.
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.
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.
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.
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.
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.
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.
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`.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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())`.
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.
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.
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.
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.
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()
});
});