The MERN Stack is a JavaScript-based technology stack used to build modern full-stack web applications.
- Consists of MongoDB, Express.js, React, and Node.js.
- Enables end-to-end development using JavaScript for both the frontend and backend.
1. Who is a MERN Stack Developer?
A MERN Stack Developer is a skilled programmer who specializes in building web applications using four key technologies: MongoDB, Express, React, and Node.js. These technologies work together to create both the front-end (what the user sees and interacts with) and back-end (the server-side logic that powers the application) of a website.
2. List the abbreviation of MERN
MERN in abbreviated form is:
- Express.js
- MongoDB
- React.js
- NodeJS
3. What is React.js?
React.js is an open-source JavaScript library used to build interactive and reusable user interfaces, especially for single-page applications (SPAs).
- Developed and maintained by Meta (Facebook).
- Uses a component-based architecture for reusable UI development.
- Uses a Virtual DOM for efficient UI updates and rendering.
- Supports JSX (JavaScript XML) to write HTML-like syntax in JavaScript.
- Runs on the client side and can communicate with backend APIs.
4. Explain the MVC architecture?
MVC (Model-View-Controller) is a software architectural pattern that separates an application into three interconnected components, making it easier to develop, maintain, and scale.
Components of MVC:
- Model: Manages the application's data, business logic, and database interactions.
- View: Displays data to the user and handles the user interface (UI).
- Controller: Processes user requests, interacts with the Model, and returns the appropriate View.
Working of MVC:
- The user interacts with the View.
- The Controller receives the request and processes it.
- The Controller communicates with the Model to retrieve or update data.
- The Model returns the data to the Controller.
- The Controller sends the updated data to the View, which displays it to the user.
5. Explain the building blocks of React?
The main building blocks of React are:
- Components: Reusable pieces of UI that return JSX and help build complex interfaces.
- JSX (JavaScript XML): A syntax extension that allows you to write HTML-like code inside JavaScript.
- Props: Read-only data passed from a parent component to a child component.
- State: Component-specific data that can change over time and trigger UI updates.
- Context: A feature that allows data to be shared across multiple components without prop drilling.
- Virtual DOM: A lightweight copy of the real DOM that enables efficient UI updates by rendering only the changed parts.
6. What Is Replication In MongoDB?
Replication in MongoDB is the process of maintaining multiple copies of the same data across different MongoDB servers using replica sets.
- Ensures high availability by automatically failing over to a secondary server if the primary server fails.
- Improves data redundancy by storing multiple copies of the database.
- Supports read scaling by allowing read operations from secondary nodes (when configured).
- Helps with backup, disaster recovery, and fault tolerance.
7. What in React are Higher-Order Components (HOC)?
A Higher-Order Component (HOC) is a function that takes a component as input and returns a new component with additional functionality. It is a design pattern used in React for reusing component logic.
Common use cases of HOCs:
- Code and logic reuse across multiple components.
- Props manipulation by injecting additional props.
- State abstraction and management.
- Render hijacking to modify or control the rendered output.
- Authentication, authorization, and logging.
8. What is Reconciliation in React.js?
Reconciliation is the process React uses to update the UI efficiently when a component's props or state changes.
- React creates a new Virtual DOM and compares it with the previous Virtual DOM using a diffing algorithm.
- It identifies the differences between the two Virtual DOM trees.
- Only the changed parts are updated in the real DOM, improving rendering performance.
- This process minimizes unnecessary DOM manipulations and makes React applications faster.
9. What is Sharding in MongoDB?
Sharding is the process of distributing data across multiple servers (shards) to support large datasets and high-throughput applications.
- Enables horizontal scaling by spreading data across multiple machines.
- Distributes data at the collection level using a shard key.
- Improves read and write performance by balancing the workload across shards.
- Helps handle large amounts of data beyond the capacity of a single server.
10. What distinguishes a class component from a functional component?
Class Components | Functional Components |
|---|---|
Class component is defined using ES6 classes. | Functional component is defined using JavaScript functions. |
Extend the React.Component class. | Do not extend any class. |
Use lifecycle methods such as componentDidMount() and componentDidUpdate(). | Use Hooks (such as useEffect) to manage lifecycle behavior. |
Manage state using this.state and this.setState(). | Manage state using Hooks like useState(). |
Require the this keyword to access props, state, and methods. | Do not use the this keyword. |
11. What is the purpose of MongoDB?
MongoDB serves as a document-oriented database manager specifically crafted for the storage of substantial data volumes. It stores data in a binary JSON format and incorporates the concepts of collections and documents. Being a cross-platform, NoSQL database, MongoDB is distinguished by its high performance, scalability, and flexibility, enabling smooth querying and indexing operations.
12. What is the purpose of Express.js?
Express.js is an open-source web application framework for Node.js that simplifies the development of web applications and RESTful APIs.
- Provides a simple and flexible framework for building server-side applications.
- Handles HTTP requests, responses, and routing efficiently.
- Supports middleware for request processing, authentication, and error handling.
- Integrates easily with databases such as MongoDB and frontend frameworks like React.
- Helps build scalable and maintainable backend applications.
13. What are the data types in MongoDB?
MongoDB stores data in BSON (Binary JSON) format, which supports a variety of data types.
Common MongoDB data types include:
- Null: Represents a null value.
- Boolean: Stores true or false.
- Number: Includes integers, doubles, decimals, and long values.
- String: Stores text data.
- Date: Stores date and time values.
- Regular Expression: Stores regex patterns.
- Array: Stores multiple values in a single field.
- Embedded Document: Stores nested documents.
- ObjectId: Stores a unique identifier for each document.
- Binary Data: Stores binary files or byte arrays.
14. What is REPL In Node.js?
REPL, short for "Read Eval Print Loop," is a straightforward program designed to receive commands, assess them, and display the outcomes. Its purpose is to establish an environment akin to a Unix/Linux shell or a Windows console, allowing users to input commands and queries while receiving corresponding outputs. The functions performed by REPL include:
- READ : This reads the input provided by the user, parses it into JavaScript data structure, and stores it in the memory.
- EVAL : This executes the data structure.
- PRINT : This prints the outcome generated after evaluating the command.
- LOOP : This loops the above command until the user presses Ctrl+C twice.
15. What is meant by “Callback” in Node.js?
A callback is a function that is passed as an argument to another function and is executed after a specific task or asynchronous operation completes.
- Used to handle the result of asynchronous operations such as file reading, database queries, or API requests.
- Allows Node.js to execute other code without waiting for the current operation to finish.
- Once the operation is complete, the callback function is invoked with the result or an error.
- Commonly used in Node.js APIs, although Promises and async/await are preferred in modern applications.
16. What are pure components in MERN Stack?
A Pure Component is a React component that automatically implements a shallow comparison of props and state to determine whether it should re-render.
- Extends React.PureComponent instead of React.Component.
- Performs a shallow comparison of props and state before re-rendering.
- Prevents unnecessary re-renders when the props and state have not changed.
- Improves application performance by reducing unnecessary rendering.
- Functional components can achieve similar behavior using React.memo().
17. How does Node.js handle Child Threads?
Node.js executes JavaScript on a single thread using an event loop to handle asynchronous operations efficiently.
- Asynchronous tasks such as file system operations, DNS lookups, and some cryptographic functions are handled by libuv's thread pool in the background.
- These background threads do not block the main event loop, allowing Node.js to process other requests concurrently.
- For CPU-intensive tasks, Node.js provides the Worker Threads module to execute JavaScript in separate threads.
- This architecture enables Node.js to handle many concurrent requests while keeping the main thread responsive.
18. What are some features of MongoDB?
Some key features of MongoDB are:
- Indexing: Supports single-field, compound, unique, geospatial, text, and hashed indexes for faster queries.
- Aggregation: Provides an aggregation framework for processing and analyzing data through pipelines.
- TTL Indexes: Automatically removes documents after a specified period using Time-To-Live (TTL) indexes.
- File Storage: Uses GridFS to efficiently store and manage large files and their metadata.
- Sharding: Distributes data across multiple servers to enable horizontal scaling.
- Replication: Maintains multiple copies of data using replica sets for high availability and fault tolerance.
19. What is Prop drilling?
When developing a React application, a deeply nested component often needs to consume data provided by another component much higher in the hierarchy. The simplest approach is to pass a prop from one component to the next, traversing the hierarchy from the source component to the deeply nested one. This process is referred to as prop drilling.
20. How do you manage packages in your node.js project?
Packages in a Node.js project are managed using package managers such as npm (default) or Yarn.
- package.json: Stores project metadata, scripts, and dependency information.
- package-lock.json: Locks the exact versions of installed packages to ensure consistent installations across different environments.
- npm: Installs, updates, removes, and manages project dependencies.
- Yarn: An alternative package manager that provides similar functionality with performance and workflow enhancements.
- Dependencies can be installed using commands such as npm install or yarn add.
21. What is JSX in React.js?
A syntactic extension to JavaScript, provides access to the full capability of JavaScript. React components are constructed using JSX, where any JavaScript expression can be incorporated by enclosing it in curly braces. After compilation, JSX expressions are transformed into standard JavaScript objects. Consequently, JSX can be assigned to variables, used as arguments, returned from functions, and employed within if statements and for loops.
22. How to handle routing in Express JS?
Express.js manages routing through the use of the express.Router() method. This method yields an instance of a router, enabling the definition of routes for the application. Below is an illustration of how to define a basic route using this router:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('Hello, World!')
})
module.exports = router
23. What is the virtual DOM in React?
The virtual DOM serves as a JavaScript representation of the real DOM (Document Object Model) employed by React to enhance rendering performance. When a modification occurs in the virtual DOM, React conducts a comparison between the new and old virtual DOMs. Subsequently, only the altered parts are updated, contributing to a faster and more efficient rendering process.
//A simple example of updating the virtual DOM in React:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={handleClick}>Click me!</button>
</div>
);
}
24. What is middleware in Node.js and how is it used?
In Node.js, middleware is a function that takes in the request and response objects, as well as the next middleware function in the application's request-response cycle. It can be employed to alter the request or response objects, as well as to execute various tasks such as logging, authentication, and error handling.
//Here's an example of a middleware function that logs the request method and URL:
function logMiddleware(req, res, next) {
console.log(`[${req.method}] ${req.url}`);
next();
}
app.use(logMiddleware);
25. What is RESTful API?
A RESTful API is an architectural style for constructing web APIs. It utilizes HTTP methods like GET, POST, PUT, and DELETE to execute CRUD (create, read, update, delete) operations on resources, identifying these resources through URLs. A key characteristic of a RESTful API is its statelessness, signifying that each request carries all the essential information for its completion.
26. Explain the event loop in Node.js.
The event loop is a mechanism in Node.js that enables non-blocking, asynchronous I/O while executing JavaScript on a single thread.
- Continuously monitors the event queue for pending callbacks.
- Executes callback functions when the call stack becomes empty.
- Works with libuv to handle asynchronous operations such as file system access, network requests, and timers.
- Allows Node.js to process multiple requests efficiently without creating a new thread for each request.
- Forms the core of Node.js's asynchronous and event-driven architecture.
27. What are Node.js streams?
Streams in Node.js are instances of EventEmitter designed for handling streaming data. They prove particularly useful in managing and manipulating large files, such as videos or mp3s, over the network. Streams employ buffers as temporary storage. There are primarily four main types of streams:
- Writable: Streams to which data can be written, exemplified by `fs.createWriteStream()`.
- Readable: Streams from which data can be read, as illustrated by `fs.createReadStream()`.
- Duplex: Streams that are both Readable and Writable, exemplified by `net.Socket`.
- Transform: Duplex streams, capable of modifying or transforming data as it is both written and read, such as `zlib.createDeflate()`.
28. What are Node.js buffers?
A Buffer in Node.js is a built-in object used to store and manipulate binary data. It represents a fixed-size sequence of bytes allocated outside the V8 JavaScript engine.
- Used to handle binary data such as files, images, network packets, and streams.
- Have a fixed size and cannot be resized after creation.
- Support various character encodings, such as UTF-8, ASCII, and Base64.
- Commonly used with streams for efficient reading and writing of binary data.
- Inherit from the Uint8Array class and provide additional methods for binary data manipulation.
29. Why use Express.js over Node.js?
Express.js is a lightweight web framework built on top of Node.js that simplifies backend development by providing additional features and utilities.
Advantages of Express.js over Node.js:
- Simplifies routing with a built-in routing system.
- Provides middleware support for request processing, authentication, and error handling.
- Makes it easier to build RESTful APIs and web applications.
- Reduces boilerplate code compared to using the native Node.js HTTP module.
- Improves code organization, scalability, and maintainability.
- Integrates easily with databases, template engines, and third-party libraries.
Note: Node.js is the runtime environment, while Express.js is a framework that runs on top of Node.js to simplify server-side development.
30. What is MongoDB?
MongoDB is an open-source, NoSQL document-oriented database designed to store and manage large volumes of data efficiently.
- Stores data in BSON (Binary JSON) documents with flexible schemas.
- Organizes data into collections and documents instead of tables and rows.
- Provides high performance, scalability, and flexibility.
- Supports features such as secondary indexes, aggregation, range queries, sorting, and geospatial indexing.
- Enables horizontal scaling through sharding and high availability through replication.
- Developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL).
31. What is a Collection in MongoDB?
A collection in MongoDB is a group of related documents, similar to a table in a relational database.
- Stores multiple documents within a database.
- Documents in the same collection can have different fields and structures because MongoDB uses a flexible schema.
- Collections do not enforce a fixed schema by default.
- Used to organize related data efficiently within a MongoDB database.
32. Explain the term “Indexing” in MongoDB.
In MongoDB, indexes play a crucial role in optimizing query resolution. Essentially, an index stores a compact portion of the dataset in a format conducive to efficient traversal. It retains the values of a specific field or set of fields, organized based on the specified field values within the index.
33. What are forms in React?
Forms in React are used to collect and manage user input through form elements such as text fields, checkboxes, radio buttons, dropdowns, and buttons.
- Allow users to interact with the application by entering and submitting data.
- Commonly used for user authentication, searching, filtering, registration, and data submission.
- Can be managed using controlled components, where form data is managed by React state.
- Can also be managed using uncontrolled components, where form data is handled using DOM references (ref).
34. Explain the lifecycle methods of components.
React class components have lifecycle methods that are executed at different stages of a component's life.
- constructor(): Initializes the component's state and binds event handlers.
- componentDidMount(): Invoked after the component is rendered and added to the DOM. Commonly used for API calls and subscriptions.
- shouldComponentUpdate(): Determines whether the component should re-render by returning true or false.
- componentDidUpdate(): Invoked after the component updates due to changes in props or state.
- componentWillUnmount(): Invoked just before the component is removed from the DOM. Used for cleanup tasks such as removing event listeners or clearing timers.
- componentDidCatch(): Handles JavaScript errors in child components using error boundaries.
35. What is Redux?
Redux is an open-source JavaScript library used for managing the state of an application in a predictable and centralized way.
- Provides a single store to manage the application's global state.
- Uses actions, reducers, and a store to update and manage state.
- Enables predictable state changes through a unidirectional data flow.
- Commonly used with React for managing complex application state.
- Simplifies state sharing across multiple components and improves application maintainability.
36. What are the components of Redux?
The main components of Redux are:
- Store: Holds the application's global state.
- Actions: Plain JavaScript objects that describe what state change should occur.
- Reducers: Pure functions that determine how the state changes in response to actions.
- Dispatch: Sends actions to the store, triggering the appropriate reducer to update the state
37. What is React Router?
React Router is a routing library for React that enables navigation between different components or pages in a single-page application (SPA) without reloading the browser.
- Maps URLs to React components.
- Supports client-side routing for faster navigation.
- Provides components such as BrowserRouter, Routes, Route, and Link.
- Supports dynamic routing, nested routes, route parameters, and protected routes.
- Improves the user experience by enabling seamless page navigation.
38. Why do we need to React Router?
React Router is used to enable client-side routing in React applications, allowing users to navigate between different pages without reloading the browser.
- Enables navigation between multiple views in a single-page application (SPA).
- Maps URLs to specific React components.
- Provides faster and smoother navigation by avoiding full page reloads.
- Supports features such as nested routes, dynamic routes, and route parameters.
- Helps maintain a consistent user experience and application structure.
39 What is the difference between Shadow DOM and Virtual DOM?
Shadow DOM | Virtual DOM |
|---|---|
Shadow DOM is a web standard used to encapsulate HTML, CSS, and JavaScript within a component. | Virtual DOM is a lightweight JavaScript representation of the real DOM used by React. |
Provides DOM and style encapsulation, preventing style and markup conflicts. | Improves rendering performance by minimizing updates to the real DOM. |
Used in Web Components and supported by modern browsers. | Used internally by React for efficient UI updates. |
Creates an isolated DOM tree attached to an element. | Compares the previous and current Virtual DOM using a diffing algorithm and updates only the changed parts of the real DOM. |
Focuses on component encapsulation. | Focuses on performance optimization. |
40. Is Node.js entirely single-threaded?
No, Node.js is not entirely single-threaded. While JavaScript execution runs on a single thread, Node.js uses an event-driven, non-blocking I/O model to handle multiple operations concurrently.
- JavaScript code executes on a single thread.
- Asynchronous I/O operations are handled by libuv using the operating system or a background thread pool.
- The event loop processes completed asynchronous tasks without blocking the main thread.
- For CPU-intensive tasks, Node.js provides the Worker Threads module to execute JavaScript in separate threads.
41. What do you mean by Temporal Dead Zone in ES6?
The Temporal Dead Zone (TDZ) is the period between entering a block scope and the point where a let or const variable is declared and initialized. During this period, the variable exists but cannot be accessed.
- Applies only to let and const, not var.
- Accessing a let or const variable before its declaration results in a ReferenceError.
- var variables are hoisted and initialized with undefined, so they can be accessed before their declaration.
console.log(varNumber); // undefined
console.log(letNumber); // ReferenceError: Cannot access 'letNumber' before initialization
var varNumber = 9;
let letNumber = 1;
42. How to Connect Node.js to a MongoDB Database?
You can connect Node.js to MongoDB using the Mongoose library, which provides an Object Data Modeling (ODM) layer for MongoDB.
Steps:
- Install the required packages using npm install mongoose.
- Import the mongoose module.
- Connect to the MongoDB server using mongoose.connect().
- Define a schema and create a model.
- Use the model to perform CRUD operations.
const mongoose = require("mongoose");
mongoose
.connect("mongodb://127.0.0.1:27017/newCollection")
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("Connection failed:", err));
const contactSchema = new mongoose.Schema({
email: String,
query: String,
});
const Contact = mongoose.model("Contact", contactSchema);
43. How to connect Node.js with React.js?
React and Node.js are typically connected using REST APIs or GraphQL APIs. React sends HTTP requests to the Node.js backend, and the backend processes the request and returns a response.
Steps:
- Create a backend API using Node.js and Express.js.
- Start the backend server on a separate port (for example, http://localhost:5000).
- Use fetch() or Axios in the React application to call the backend API.
- Process the response and update the React UI.
Backend (Node.js + Express):
const express = require("express");
const app = express();
app.get("/api/message", (req, res) => {
res.json({ message: "Connected to React" });
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Frontend (React):
import { useEffect, useState } from "react";
function App() {
const [message, setMessage] = useState("");
useEffect(() => {
fetch("http://localhost:5000/api/message")
.then((res) => res.json())
.then((data) => setMessage(data.message));
}, []);
return <h2>{message}</h2>;
}
export default App;
44. Can you elaborate on the MongoDB Aggregation Pipeline?
The MongoDB Aggregation Pipeline serves as a framework for data processing and transformation within MongoDB. It involves a series of sequential stages, facilitating operations like filtering, projection, grouping, and sorting on documents. Each stage in the pipeline processes the data and forwards the results to the subsequent stage, culminating in the generation of the final output.
45. How can you use the like operator to query MongoDB?
MongoDB does not provide a direct LIKE operator like SQL. Instead, it uses the $regex operator to perform pattern matching.
Example:
db.myCollection.find({
name: { $regex: /^Nick/ }
});
The above query returns all documents where the name field starts with "Nick".
Common $regex patterns:
- ^Nick : Starts with Nick.
- Nick$ : Ends with Nick.
- Nick : Contains Nick.
/Nick/i: Performs a case-insensitive search.
46. Name a few techniques to optimize React app performance.
Some common techniques to optimize React application performance are:
- Memoization: Use React.memo, useMemo, and useCallback to avoid unnecessary re-renders and recalculations.
- Virtualization: Use libraries such as react-window or react-virtualized to efficiently render large lists.
- Code Splitting: Split the application into smaller bundles and load them only when required.
- Lazy Loading: Use React.lazy() and Suspense to load components on demand.
- Optimize Re-renders: Use React.memo, PureComponent, or shouldComponentUpdate() to prevent unnecessary rendering.
- Avoid Unnecessary State Updates: Update state only when necessary to reduce re-renders.
- Server-Side Rendering (SSR): Render pages on the server to improve initial load time and SEO.
- Use Proper Keys: Provide unique key props when rendering lists to improve React's reconciliation process.
47. What is the purpose of module.exports?
The module.exports object in Node.js is used to export functions, objects, classes, or variables from a module so they can be imported and reused in other files.
- Enables code reusability by sharing functionality across multiple modules.
- Works with the require() function to import exported members.
- Helps organize code into modular and maintainable files.
- Can export a single value or multiple values from a module.
48. Can you explain CORS?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that allows a web application running on one origin (domain, protocol, or port) to access resources from another origin.
- Uses HTTP headers to control cross-origin requests.
- Helps prevent unauthorized cross-origin access while allowing approved requests.
- Is enforced by web browsers as part of the Same-Origin Policy.
- Can be configured on the server by setting appropriate CORS headers, such as Access-Control-Allow-Origin.
- Commonly used when a frontend application and backend API are hosted on different domains or ports.
49. What is DOM diffing?
DOM diffing is the process React uses to compare the previous Virtual DOM with the new Virtual DOM to identify changes in the UI.
- Uses a diffing algorithm to detect differences between the two Virtual DOM trees.
- Identifies only the components or elements that have changed.
- Updates only the changed parts of the real DOM, instead of re-rendering the entire page.
- Reduces unnecessary DOM manipulations, improving rendering performance and user experience.
- Forms the core of React's reconciliation process.
50. What are the benefits of using JSX in React?
JSX provides several benefits that make React development easier and more efficient.
- Allows developers to write HTML-like syntax within JavaScript, making code more readable.
- Makes UI code easier to understand and maintain.
- Supports embedding JavaScript expressions using curly braces {}.
- Is transpiled into standard JavaScript by tools such as Babel.
- Helps detect syntax errors during compilation.
- Improves developer productivity by simplifying the creation of React components.