0% found this document useful (0 votes)
286 views71 pages

Mean Stack Questions

mean-stack-questions MTECH SEM 2

Uploaded by

suneel sekhar
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)
286 views71 pages

Mean Stack Questions

mean-stack-questions MTECH SEM 2

Uploaded by

suneel sekhar
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/ 71

Mean stack questions

 ffffjhjhjhjhj

 1-In Node.js, Modules are the blocks of encapsulated code that communicate with an
external application on the basis of their related functionality. Modules can be a single
file or a collection of multiple files/folders. The reason programmers are heavily reliant
on modules is because of their reusability as well as the ability to break down a complex
piece of code into manageable chunks.

Modules are of three types:

Core Modules

local Modules

Third-party Modules

Core Modules: Node.js has many built-in modules that are part of the platform and come with
Node.js installation. These modules can be loaded into the program by using the required
function.

Syntax:

const module = require('module_name');

The require() function will return a JavaScript type depending on what the particular module
returns. The following example demonstrates how to use the Node.js http module to create a web
server.

javascript

const http = require('http');


http.createServer(function (req, res) {

res.writeHead(200, { 'Content-Type': 'text/html' });

res.write('Welcome to this page!');

res.end();

}).listen(3000);

In the above example, the require() function returns an object because the Http module returns its
functionality as an object. The function http.createServer() method will be executed when
someone tries to access the computer on port 3000. The res.writeHead() method is the status
code where 200 means it is OK, while the second argument is an object containing the response
headers. The following list contains some of the important core modules in Node.js:

Core
Modules Description

http creates an HTTP server in Node.js.

assert set of assertion functions useful for testing.

fs used to handle file system.

path includes methods to deal with file paths.

process provides information and control about the current Node.js process.

os provides information about the operating system.


querystring utility used for parsing and formatting URL query strings.

url module provides utilities for URL resolution and parsing.

Local Modules: Unlike built-in and external modules, local modules are created locally in your
Node.js application. Let’s create a simple calculating module that calculates various operations.
Create a calc.js file that has the following code:

Filename: calc.js

javascript

exports.add = function (x, y) {

return x + y;

};

exports.sub = function (x, y) {

return x - y;

};

exports.mult = function (x, y) {

return x * y;
};

exports.div = function (x, y) {

return x / y;

};

Since this file provides attributes to the outer world via exports, another file can use its exported
functionality using the require() function.

Filename: index.js

javascript

const calculator = require('./calc');

let x = 50, y = 10;

console.log("Addition of 50 and 10 is "

+ calculator.add(x, y));
console.log("Subtraction of 50 and 10 is "

+ calculator.sub(x, y));

console.log("Multiplication of 50 and 10 is "

+ calculator.mult(x, y));

console.log("Division of 50 and 10 is "

+ calculator.div(x, y));

Step to run this program: Run the index.js file using the following command:

node index.js

Output:

Addition of 50 and 10 is 60

Subtraction of 50 and 10 is 40

Multiplication of 50 and 10 is 500

Division of 50 and 10 is 5

Note: This module also hides functionality that is not needed outside of the module.

Third-party modules: Third-party modules are modules that are available online using the
Node Package Manager(NPM). These modules can be installed in the project folder or globally.
Some of the popular third-party modules are Mongoose, express, angular, and React.
Example:

npm install express

npm install mongoose

npm install -g @angular/cli

What are the features of ReactJpdated : 14


Dec, 2023222222222

Created by Facebook, ReactJS is a JavaScript library designed


for crafting dynamic and interactive applications, elevating
UI/UX for web and mobile platforms. Operating as an open-
source, component-based front-end library, React is
dedicated to UI design and streamlines code debugging by
employing a component-oriented approach.
We will discuss about the following featured of React:
Table of Content
 JSX(JavaScript Syntax Extension):

 Virtual DOM:

 One-way Data Binding:

 Performance:

 Extension:

 Conditional Statements:

 Components:
 Simplicity:
Let’s understand each of them in detail:
1. JSX(JavaScript Syntax Extension):
JSX is a combination of HTML and JavaScript. You can embed
JavaScript objects inside the HTML elements. JSX is not
supported by the browsers, as a result, Babel compiler
transcompile the code into JavaScript code. JSX makes codes
easy and understandable. It is easy to learn if you know HTML
and JavaScript.

const name="GeekforGeeks";
const ele = <h1>Welcome to {name}</h1>;
2. Virtual DOM:
DOM stands for Document Object Model. It is the most
important part of the web as it divides into modules and
executes the code. Usually, JavaScript Frameworks updates
the whole DOM at once, which makes the web application
slow. But react uses virtual DOM which is an exact copy of
real DOM. Whenever there is a modi昀椀cation in the web
application, the whole virtual DOM is updated 昀椀rst and 昀椀nds
the di昀昀erence between real DOM and Virtual DOM.

In the above-shown 昀椀gure, when the whole virtual DOM has


updated there is a change in the child components. So, now
DOM 昀椀nds the di昀昀erence and updates only the changed part.
3. One-way Data Binding:
One-way data binding, the name itself says that it is a one-
direction 昀氀ow. The data in react 昀氀ows only in one direction
i.e. the data is transferred from top to bottom i.e. from parent
components to child components. The properties(props) in
the child component cannot return the data to its parent
component but it can have communication with the parent
components to modify the states according to the provided
inputs.

One-way Data Binding

As shown in the above diagram, data can 昀氀ow only from top
to bottom.
4. Performance:
As we discussed earlier, react uses virtual DOM and updates
only the modi昀椀ed parts. So , this makes the DOM to run
faster. DOM executes in memory so we can create separate
components which makes the DOM run faster.
5. Extension:
React has many extensions that we can use to create full-
昀氀edged UI applications. It supports mobile app development
and provides server-side rendering. React is extended with
Flux, Redux, React Native, etc. which helps us to create good-
looking UI.
6. Conditional Statements:
JSX allows us to write conditional statements. The data in the
browser is displayed according to the conditions provided
inside the JSX.
Syntax:

const age = 12;


if (age >= 10)
{
<p> Greater than { age } </p>;
}
else
{
<p> { age } </p>;
}
7. Components:
React.js divides the web page into multiple components as it
is component-based. Each component is a part of the UI
design which has its own logic and design as shown in the
below image. So the component logic which is written in
JavaScript makes it easy and run faster and can be reusable.

Multiple components

8. Simplicity:
React.js is a component-based which makes the code
reusable and React.js uses JSX which is a combination of
HTML and JavaScript. This makes code easy to understand
and easy to debug and has less code.
Steps to Create React Application:
Step 1: Create a react application by using the following
command:

npx create-react-app foldername


Step 2: Change your directory to the newly created folder.

cd foldername

Project Structure:
Example: This example uses props data to demonstrate
condiotional rendering in react

 Javascript
 Javascript
 Javascript
 Javascript
// Filename - index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(<App isPass={true} />,

document.getElementById('root'));

Step to Run the application: Open the terminal and type


the following command.

npm start
Output: If you give the value of isPass={true} in index.js,
then it will give the following output:

If the value of isPass={false} in index.js, then the


following output is displayed.
How to Create Database and Collection in
33333333333

MongoDB stores data records as documents that are stored


together in collections and the database stores one or
more collections of documents.
In this article, we will look at methods to create a database
and collection in MongoDB.
Create a MongoDB Database
To create a database in MongoDB use the “use” command.
Syntax
use database_name
Example
We have created a MongoDB database named gfgDB, as
shown in the image below:

Here, we have created a database named as “gfgDB”. If the


database doesn’t exist, MongoDB will create the database
when you store any data to it.

Note: The "use" command is also used to switch to


another database.
View all the Existing Databases
To view all existing databases in MongoDB use the “show
dbs” command.
Syntax

show dbs
This command returns a list of all the existing MongoDB
databases.

To check your current database use the “db” command


Create a Collection in MongoDB
To create a collection in MongoDB use the
createCollection() method. Collection name is passed as
argument to the method.
Syntax
db.createCollection(‘ collection_name’ );
Example
Creating collection named “Student” in MongoDB

db.createCollection('Student');
createCollection() in MongoDB
Explanation:
In the above example, Student Collection is created using
createCollection() method.

Note: In MongoDB, a collection is also created


directly when we add one or more documents to it.
Insert Documents in Collection in
MongoDB
We can insert documents in the collection using the two
methods:

insertOne()

insertMany()
Let’s understand each of these methods with examples.
insertOne() Method
insertOne() method is used to insert only one document in
the collection.
Example:

db.myNewCollection1.insertOne( { name:"geeksforgeeks" } )
Here, we create a collection named as “myNewCollection1”
by inserting a document that contains a “name” 昀椀eld with its
value in it using insertOne() method.
insertMany() method
insertMany() method is used to insert many documents in
the collection
Example:

db.myNewCollection2.insertMany([{name:"gfg",
country:"India"},

{name:"rahul", age:20}])
Here, we create a collection named as myNewCollection2 by
inserting two documents using insertMany() method.

View all the Existing Collections in a


MongoDB Database
To view all existing collections in a MongoDB database use
the “show collection command“:
Syntax

show collections
Example
This command returns a list of all the existing collections in
the gfgDB database.
Express.js Tutorial
Last Updated :444 15 Apr, 2024

Express.js is a fast, 昀氀exible and minimalist web framework


for Node.js. It’s e昀昀ectively a tool that simpli昀椀es building web
applications and APIs using JavaScript on the server side.
Express is an open-source that is developed and maintained
by the Node.js foundation.
Express.js o昀昀ers a robust set of features that enhance your
productivity and streamline your web application. It makes it
easier to organize your application’s functionality with
middleware and routing. It adds helpful utilities to Node HTTP
objects and facilitates the rendering of dynamic HTTP objects.
Why learn Express?
Express is a user-friendly framework that simpli昀椀es the
development process of Node applications. It uses JavaScript
as a programming language and provides an e昀케cient way to
build web applications and APIs. With Express, you can easily
handle routes, requests, and responses, which makes the
process of creating robust and scalable applications much
easier.
Moreover, it is a lightweight and 昀氀exible framework that is
easy to learn and comes loaded with middleware options.
Whether you are a beginner or an experienced developer,
Express is a great choice for building your application.
Express Key Features
Middleware and Routing: Express.js makes it easy to
organize your application’s functionality using middleware
and routing. Middleware functions allow you to handle
tasks like authentication, logging, and error handling.
Routing ensures that incoming requests are directed to the
appropriate handlers.
Minimalistic Design: Express.js follows a simple and
minimalistic design philosophy. This simplicity allows you
to quickly set up a server, de昀椀ne routes, and handle HTTP
requests e昀케ciently. It’s an excellent choice for building
web applications without unnecessary complexity.

Flexibility and Customization: Express.js doesn’t


impose a strict application architecture. You can structure
your code according to your preferences. Whether you’re
building a RESTful API or a full-昀氀edged web app, Express.js
adapts to your needs.

Scalability: Designed to be lightweight and scalable,


Express.js handles a large number of requests
asynchronously. Its event-driven architecture ensures
responsiveness even under heavy loads.

Active Community Support: With a thriving community,


Express.js receives regular updates and improvements.
You’ll 昀椀nd ample documentation, tutorials, and plugins to
enhance your development experience.
Getting Started Express
1. Installation: Install Express using npm:

npm install express


2. Basic Example of an Express App:

Node

const express = require('express');

const app = express();

// Define routes and middleware here


// ...

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

console.log(`Server running on port ${PORT}`);

});
Explanation:

Import the ‘express’ module to create a web application


using Node.js.

Initialize an Express app using const app = express();.

Add routes (endpoints) and middleware functions to


handle requests and perform tasks like authentication or
logging.

Specify a port (defaulting to 3000) for the server to


listen on.
Express Basic:
Introduction to Express

Steps to create Express Application

Design 昀椀rst Application using Express

How to Structure my Application in Express JS

Unique features of Express

How to send response from server to client using Node and


Express ?
Why Express ‘app’ and ‘server’ 昀椀les kept separately ?

How to implement JWT authentication in Express app

How to expire session after 1 min of inactivity in express-


session of Express JS

Express Error Handling


Express Functions:
Express express():

Expresson() Function

express.raw() Function

express.Router() Function

express.static() Function

express.text() Function

express.urlencoded() Function

express() function Complete Reference


Express Applications Function:

app.locals Property

app.mountpath Property

Mount Event

app.all() Function

app.delete() Function

app.disable() Function
app.disabled() Function

app.enable() Function

app.enabled() Function

Application Complete Reference


Express Requests Function:

req.app Property

req.baseUrl Property

req.body Property

req.cookies Property

req.fresh Property

req.accepts() Function

req.acceptsCharsets() Function

req.acceptsEncodings() Function

req.acceptsLanguages() Function

Request Complete Reference


Express Response Function:

res.app Property

res.headersSent Property

res.locals Property

res.append() Function
res.attachment() Function

res.cookie() Function

res.clearCookie() Function

res.download() Function

res.end() Function

Response Complete Reference


Express Router Function:

router.all() Function

router.METHOD() Function

router.param() function

router.route() Function

router.use() Function

Router Complete Reference


Express Advanced Topics:

Node vs Express

Middlewares in Express

How to update record in Cassandra using Express

What is the use of next() function in Express JS

How to create custom middleware in express

Why Express is used in Web Development


What is Express Generator

Express HTTP methods

How to create routes using Express and Postman?

Why Express Is Used For Enterprise App Development

REST API using the Express to perform CRUD

What is express-session middleware in Express


Advanced Concepts
Template Engines: Use template engines like EJS or Pug
for dynamic content rendering.

Error Handling: Implement custom error handling


middleware to gracefully handle exceptions.

Authentication: Integrate authentication middleware


(e.g., Passport.js) for secure user sessions.

5
As an asynchronous event-driven JavaScript runtime, Node.js is
designed to build scalable network applications. In the following
"hello world" example, many connections can be handled
concurrently. Upon each connection, the callback is 昀椀red, but if
there is no work to be done, Node.js will sleep.

CJSMJS

const { createServer } = require('node:http');const hostname = '127.0.0.1';const port =


3000;const server = createServer((req, res) => { res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain'); res.end('Hello World');});server.listen(port,
hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);});
JavaScriptCopy to clipboard

This is in contrast to today's more common concurrency model, in


which OS threads are employed. Thread-based networking is
relatively ine昀케cient and very di昀케cult to use. Furthermore, users of
Node.js are free from worries of dead-locking the process, since
there are no locks. Almost no function in Node.js directly performs
I/O, so the process never blocks except when the I/O is performed
using synchronous methods of Node.js standard library. Because
nothing blocks, scalable systems are very reasonable to develop in
Node.js.

If some of this language is unfamiliar, there is a full article on


Blocking vs. Non-Blocking.

Node.js is similar in design to, and in昀氀uenced by, systems like


Ruby's Event Machine and Python's Twisted. Node.js takes the event
model a bit further. It presents an event loop as a runtime construct
instead of as a library. In other systems, there is always a blocking
call to start the event-loop. Typically, behavior is de昀椀ned through
callbacks at the beginning of a script, and at the end a server is
started through a blocking call like EventMachine::run(). In Node.js,
there is no such start-the-event-loop call. Node.js simply enters the
event loop after executing the input script. Node.js exits the event
loop when there are no more callbacks to perform. This behavior is
like browser JavaScript — the event loop is hidden from the user.

HTTP is a 昀椀rst-class citizen in Node.js, designed with streaming and


low latency in mind. This makes Node.js well suited for the
foundation of a web library or framework.

Node.js being designed without threads doesn't mean you can't take
advantage of multiple cores in your environment. Child processes
can be spawned by using our child_process.fork() API, and are designed
to be easy to communicate with. Built upon that same interface is
the cluster module, which allows you to share sockets between
processes to enable load balancing over your cores.

The Pros and Cons of Node.JS in Web


Development
Last Updated : 08 Dec, 2022

Node.js is a platform that allows developers to build highly


scalable applications using JavaScript. It has become the
most popular language for developing real-time apps,
especially in the enterprise space where it can handle
thousands of simultaneous connections while maintaining low
latency and high performance.
Pros of Using Node.js:
1. Speed: One of the key bene昀椀ts of Node.js development is
its speed, which makes it a great choice for dynamic
applications. The runtime environment of Node.js is based on
an event loop that handles multiple concurrent requests
easily and quickly, allowing you to scale your application with
ease.
Node.js also uses non-blocking I/O (asynchronous IO), which
means that instead of waiting for each request to 昀椀nish
before processing another one, it returns immediately after
receiving the response from a previous request—allowing you
to handle many more requests at once without any
noticeable delay in performance or responsiveness!
2. Productivity: Node.js is a highly productive platform for
developing web applications. It’s a single-threaded, event-
driven environment, which makes it ideal for real-time
applications such as chat and video streaming. This makes
Node.js an ideal choice for building highly interactive
websites with Ajax functionality as well as Divi Builder
extensions that allow you to build custom themes without
having to write any PHP code or CSS 昀椀le types (like .css).
3. Error handling: Node.js has a built-in error-handling
mechanism that allows you to catch errors at runtime and do
something with them. This is similar to the try/catch
mechanism of Java and C++, but in Node, it’s easier than
ever because there are no exceptions! Errors are just thrown
as an event that can be caught by your code. You can also
use “error” objects instead of throwing errors directly into
other functions or methods if you need more control over
what happens when an error occurs (e.g., logging).
4. Cost-e昀昀ectiveness: There are several bene昀椀ts to using
Node.js development services, including cost-e昀昀ectiveness.
The main reason why companies choose this technology is
because of its cost savings and time savings.
Cost Savings: With a comprehensive cloud solution from
NodeStack, you can save money in many ways including:
• Lowering your IT costs by reducing the amount of hardware
required for server deployments;
• Decreasing operating expenses related to software
licensing;
• Eliminating maintenance costs associated with upgrading or
patching existing applications or servers
5. Faster development: Node.js is a platform for building
fast websites and web apps. It’s also the most popular
platform for building microservices, which means you can use
it to build applications that have many small parts that work
together as one system.
Node.js allows developers to create high-performance
applications in a fraction of the time required by other
languages and platforms like Java or C++ (which are both
very good at handling large amounts of data). This makes it
easy to launch new products quickly while still maintaining
quality control over each part of your application since each
component will be tested individually before being added to
the full stack
6. Better performance in slow network environments:
As you might expect, the single-threaded nature of node.js
makes it more suitable for handling slow network connections
and other tasks that require a lot of processing power. The
non-blocking I/O model used by NodeJS allows it to handle
many concurrent connections without waiting for other
threads or processes to 昀椀nish their work before continuing on
with yours. This makes your application run faster than if you
were using a language like PHP or Java which are multi-
threaded and can only do one thing at a time (or not even
that).
7. Highly scalable applications: Node.js is an open-
source, cloud-based platform that o昀昀ers many bene昀椀ts to
developers. It is highly scalable and responds quickly to
changes in the data layer, allowing you to build large
applications with ease. The following are some of the ways
you can scale your Node.js application:
• Use a cloud provider such as Amazon Web Services (AWS)
or Microsoft Azure Cloud Platform (MCP). These providers
o昀昀er dedicated resources that will help reduce costs while
increasing performance—and they’re free!
• Run your code on-premises using VMware vCloud Air or
EMC VNXe environment management software solutions
(EMSS). This method allows you to access VM instances
within VMWare environments without having any additional
hardware requirements because all required hardware has
been precon昀椀gured into them already by their respective
manufacturers
However, keep in mind that this method may not be suitable
for high-performance applications since it requires signi昀椀cant
resources from both servers which could lead up to scalability
issues if not properly managed correctly.”
8. Full-stack JS developer requirement: Node.js is a full-
stack framework, which means it can be used in multiple
programming languages and frameworks. It’s not a
replacement for Java or PHP, but rather an alternative to
them if you want to build web applications that need to scale
on the server side (such as e-commerce websites). Node.js
isn’t meant to replace existing languages like Python or
Ruby; instead, it o昀昀ers an easier way for developers who
have never used JavaScript before but still want access to
some of its features like asynchronous processing and non-
blocking I/O operations—which means no more waiting
around while your program runs!
9. Node.js is a reliable, high-performing, and highly
昀氀exible platform for developing dynamic web apps:
Node.js is a fast and scalable platform for developing web
applications, used to build real-time apps, server-side, and
networking applications. It is an open-source, cross-platform
runtime environment that allows you to build scalable
networked applications using JavaScript.
Node.js has been designed from the ground up for building
fast web servers with low latency in mind – by utilizing
asynchronous I/O in combination with a library called libuv
which provides event loop abstraction over libev or kqueue
implementations (you can choose whichever one suits your
needs). This enables developers to write asynchronous code
without having to worry about thread management or
context-switching issues that arise when using other methods
such as callbacks or promises; all this makes it possible for
Node.js developers who work on top of any framework like
Laravel 5 where your backend code will be executed within
its own process space under its own identity identi昀椀er so
there won’t be any clashes between di昀昀erent environments
such as local host vs remote host etc.
The Cons of Using Node.js:
1. Asynchronous Programming Model: Asynchronous
programming is a form of programming in which program
execution proceeds without waiting for all program elements
to be processed. In asynchronous programming, program
elements that can run independently of other elements are
processed in parallel, and program elements that cannot run
independently are processed sequentially.
2. Unstable API: An unstable API is one that is subject to
change at any time. This can be a problem for developers
who are relying on the API to remain constant in order to
maintain their own software. An unstable API can also lead to
software that is di昀케cult to maintain and upgrade.
If you’re using node.js, you need to be aware that the API is
unstable. That means that it’s subject to change at any time,
and you could potentially break your code if you’re not
careful. It’s important to keep up to date with the latest
changes and to be prepared for breaking changes.
3. Dealing with Relational Database: A relational
database is a database that stores data in tables that are
related to each other. This is in contrast to a non-relational
database, which does not have this concept of relations
between tables. Relational databases are the most widely
used type of database, and they are well-suited for many
applications. However, they can be more di昀케cult to work with
than non-relational databases, and this can be a pain point
for developers.
Node.js is a JavaScript runtime that is well-suited for working
with relational databases. Node.js also has a module called
the mysql module that allows you to connect to a MySQL
database and perform database operations.
However, this can also be a pain point, as some libraries are
more di昀케cult to use than others. They can be more di昀케cult
to work with than non-relational databases. Node.js can make
working with relational databases easier, but it can also be a
pain point.
Still, If you want non-relational persistence just simply de-
normalize a relational database. If you use a relational DB
with Node.js I recommend this ORM.
4. Lacks a Strong Library Support System: Node.js lacks
strong library support. Because Node.js is relatively new,
there are fewer high-quality libraries available for it
compared to other programming languages. This can make it
more di昀케cult to 昀椀nd the right library for a given task, and it
can also make it more di昀케cult to get started with Node.js
development. Additionally, the libraries that are available for
Node.js often have fewer features than their counterparts in
other languages. This makes it di昀케cult for the developers to
even implement the common programming tasks using
Node.js also it makes development more challenging, and it
can also lead to more bugs and issues in production code.
5. Not Suited for CPU-intensive Tasks: Node.js
applications are single-threaded, which means that they can
only use one CPU core at a time. This can be a bottleneck for
applications that are CPU-intensive.
As we know, Node.js is a runtime environment that executes
JavaScript on the server side. Being a front-end programming
language, JavaScript uses a single thread to process tasks
fast. Threading is not required for it to work, because tasks in
JavaScript are lightweight and take little CPU.
A non-blocking input/output model means that Node.js
answers the client call to start a request and waits for I/O
tasks to complete in the background while executing the rest
and then returns to I/O tasks using callbacks. Processing
requests asynchronously, Node executes JS code on its single
thread on an event basis. That is what is called an event loop.
This event loop problem occurs when Node.js receives a CPU-
intensive task.
Whenever a heavy request comes to the event loop, Node.js
will set all the CPU available to process it in the 昀椀rst queue,
and then execute other pending requests in a queue. As a
result, it will bottleneck in processing. That’s why it’s not
suitable for High intensive CPU tasks.
However, In 2018 multithreading was introduced with the
worker threads module in Node.js after the 10.5.0 update,
Worker threads allow for running several Node.js instances
inside a process sharing the same system memory. This
solution can help solve some CPU-bound tasks, but it does
not make Node.js a multithreading high-performance
language.
6. Memory Leaks: If your web application is not coded well,
it can be defenseless against to memory leaks.
A memory leak is when a piece of code allocates memory but
never frees it, resulting in the memory being “leaked.” This
can eventually lead to the Node.js process running out of
memory and crashing.
There are a number of ways to prevent memory leaks in
Node.js. The 昀椀rst is to make sure that all code that allocates
memory also frees it. This can be di昀케cult to do in a complex
application, but it is crucial. The second is to use a tool like
heapdump to take periodic snapshots of the Node.js
process’s memory usage. This can help identify areas where
memory is being leaked. Finally, it is important to keep an
eye on the Node.js process’s memory usage and be prepared
to restart it if it starts to get too high.
While memory leaks can be a problem, there are ways to
prevent them. By being careful with memory allocation and
using tools like heapdump, it is possible to keep Node.js
applications running smoothly.
8

MongoDB is a popular NoSQL document-oriented database


management system, known for its 昀氀exibility, high
performance, high availability, and multi-storage engines.
The term NoSQL means non-relational. It means that
MongoDB isn’t based on a table-like relational database
structure. It is used by Adobe, Uber, IBM, and Google. In this
article, we will delve into the MongoDB architecture,
exploring its key components and how they work together.
Key Features of MongoDB
Document-oriented Database

Stores data in BSON-like documents.

Schema Less database.

It provides horizontal scalability with the help of


sharding.
It provides high availability and redundancy with the help
of replication.

It allows one to perform operations on the grouped data


and get a single result or computed result.

It has very high performance.


MongoDB Vs RDBMS
MongoDB RDBMS

It is a non-relational, document-oriented
It is a Relational database management
database management system and works
system and works on relational databases.
on document-based database

MongoDB uses a document structure to The table structure is used to store the data in
store the data. RDBMS

It has schema-less databases. It uses the schema structure.

Supports MongoDB Query Language


Supports SQL query language.
(MQL) of BSON type

It follows the CAP theorem. It follows ACID properties.

In MongoDB, the database can be scaled In RDBMS, we can scale the database
horizontally. vertically.

MongoDB Architecture and its


Components
MongoDB’s architecture design involves several important
parts that work together to create a strong and 昀氀exible
database system. these are the following MongoDB’s
architecture
1. Drivers & Storage Engine
MongoDB store the data on the server but that data we will
try to retrieve from our application. So that time how the
communication is happening between our application and
MongoDB server.
Any application which is written in python, .net and java or
any kind of frontend application, these application are trying
to access the data from these physical storage in server. First
they will interact with driver which will communicate with
MongoDB server. What happen is once the request is going
from the frontend application through the driver then
driver will change appropriate query by using query engine
and then the query will get executed in MongoDB data
model. Left side is security which provides security to the
database that who will access the data and right side is
management this management will manage all these things.
Drivers
Drivers are client libraries that o昀昀er interfaces and
methods for applications to communicate with MongoDB
databases. Drivers will handle the translation of documents
between BSON objects and mapping application structures.
.NET, Java, JavaScript, Node.js, Python, etc are some of the
widely used drives supported by MongoDB.
Storage Engine
The storage engine signi昀椀cantly in昀氀uences the performance
of applications, serving as an intermediary between the
MongoDB database and persistent storage, typically disks.
MongoDB supports di昀昀erent storage engines:

MMAPv1 – It is a traditional storage engine based on


memory mapped 昀椀les. This storage engine is optimized
for workloads with high volumes of read operations,
insertions, and in-place updates. It uses B-tress to store
indexes. Storage Engine works on multiple reader single
writer lock. A user cannot have two write calls to be
processes in parallel on the same collection. It is fast for
reads and slow for writes.

Wired Tiger – Default Storage Engine starts from


MongoDB 3version. No locking Algorithms like hash
pointer. It yields 7x-10x better write operations and 80%
of the 昀椀le system compression than MMAP.
InMemory – Instead of storing documents on disk, the
engine uses in-memory for more predictable data
latencies. It uses 50% of physical RAM minimum 1 GB as
default. It requires all its data. When dealing with large
datasets, the in-memory engine may not be the most
suitable choice.
2. Security
Authentication

Authorization

Encryption on data

Hardening (Ensure only trusted hosts have access)


3. MongoDB Server
It serves as the central element and is in charge of
maintaining, storing, and retrieving data from the
database through a number of interfaces. The system’s heart
is the MongoDB server. Each mongod server instance is in
charge of handling client requests, maintaining data storage,
and performing database operations. Several mongod
instances work together to form a cluster in a typical
MongoDB setup.
4. MongoDB Shell
For dealing with MongoDB databases, MongoDB provides the
MongoDB Shell command-line interface (CLI) tool. The
ability to handle and query MongoDB data straight from the
terminal is robust and 昀氀exible. After installing MongoDB,
you may access the MongoDB Shell, often known as mongo.
It interacts with the database using JavaScript-based syntax.
Additionally, it has built-in help that shows details about
possible commands and how to use them.
5. Data Storage in MongoDB
5.1 Collections
A database can contain as many collections as it wishes, and
MongoDB stores data inside collections.
As an example, a database might contain three collections a
user’s collection, a blog post collection, and a
comments collection. The user collection would hold user
data and documents, the blog post collection would hold blog
posts and documents, and the comments collection would
hold documents related to comments. This would allow for
the easy retrieval of all the documents from a single
collection.
5.2 Documents
Documents themselves represent the individual records in a
speci昀椀c collection.
For example inside the blog posts collection we’d store a lot
of blog post documents and each one represents a single
blog post now the way that data is structured inside a
document looks very much like a JSON object with key value
pairs but actually it’s being stored as something called BSON
which is just binary JSON.
6. Indexes
Indexes are data structures that make it simple to navigate
across the collection’s data set. They help to execute queries
and 昀椀nd documents that match the query criteria without a
collection scan.
These are the following di昀昀erent types of indexes in
MongoDB:
6.1 Single 昀椀eld
MongoDB can traverse the indexes either in the ascending
or descending order for single-昀椀eld index

db.students.createIndex({“item”:1})
In this example, we are creating a single index on the item
昀椀eld and 1 here represents the 昀椀led is in ascending order.
A compound index in MongoDB contains multiple single
昀椀led indexes separated by a comma. MongoDB restricts the
number of 昀椀elds in a compound index to a maximum of 31.

db.students.createIndex({“item”: 1, “stock”:1})
Here, we create a compound index on item: 1, stock:1
6.2 Multi-Key
When indexing a 昀椀led containing an array value, MongoDB
creates separate index entries for each array component.
MongoDB allows you to create multi-key indexes for arrays
containing scalar values, including strings, numbers, and
nested documents.

db.students.createIndex({<filed>: <1 or -1>})


6.3 Geo Spatial
Two geospatial indexes o昀昀ered by MongoDB are called 2d
indexes and 2d sphere indexes. These indexes allow us to
query geospatial data. On this case, queries intended to
locate data stored on a two-dimensional plane are supported
by the 2d indexes. On the other hand, queries that are used
to locate data stored in spherical geometry are supported by
2D sphere indexes.
6.4 Hashed
To maintain the entries with hashes of the values of the
indexed 昀椀eld we use Hash Index. MongoDB supports hash
based sharding and provides hashed indexes.

db.<collection>.createIndex( { item: “hashed” } )


7. Replication
Within a MongoDB cluster, data replication entails keeping
several copies of the same data on various servers or nodes.
Enhancing data availability and dependability is the main
objective of data replication. A replica may seamlessly
replace a failing server in the cluster to maintain service
continuity and data integrity.
Primary Node (Primary Replica): In a replica set, the
primary node serves as the main source for all write
operations. It’s the only node that accepts write requests.
The main node is where all data modi昀椀cations begin and
are implemented initially.

Secondary Nodes: Secondary nodes duplicate data from


the primary node (also known as secondary replicas). They
are useful for dispersing read workloads and load
balancing since they are read-only and mostly utilized for
read activities.
8. Sharding
Sharding is basically horizontal scaling of databases as
compared to the traditional vertical scaling of adding more
CPUS and ram to the current system.
For example, you have huge set of 昀椀les you might segregate
it into smaller sets for ease. Similarly what mongo database
does is it segregates its data into smaller chunks to improve
the e昀케ciency.
you have a machine with these con昀椀guration and mongo db
instance running on it storing 100 million documents.
Now with time your data will grow in your mongo db instance
and suppose 100 million extra documents get added. Now to
manage the processing of these extra records you might
need to add extra ram, extra storage and extra CPU to the
server. Such type of scaling is called vertical scaling.
Now consider another situation if you have 4 small machines
with small con昀椀gurations. You can divide 200 million of
document into each of the server such that each of the server
might hold around 50 million documents. By dividing the data
into multiple servers you have reduced the computation
requirements and such kind of scaling is known as horizontal
scaling and this horizontal scaling is known as sharding in
mongo and each of the servers S1, S2, S3, S4 are the shards.
The partioning of data in a sharded environment is done on a
range based basis by deciding a 昀椀eld as a shard key.
Conclusion
The architecture of MongoDB has been thoroughly examined
in this extensive article, including its essential parts, data
storage, replication, sharding, high availability, security,
scalability, and performance optimization. MongoDB is a top
choice for a wide range of applications, from small-scale
initiatives to massive, data-intensive systems, due to its
adaptable and potent design. To fully utilize MongoDB and
create reliable, scalable, and secure solutions, developers
and administrators must have a thorough understanding of
the database’s architecture.

Express.js router.METHOD() Function


Last 917 Mar, 2023

The router.METHOD() method provides the routing


functionality in Express, where METHOD is one of the HTTP
methods, such as GET, PUT, POST, and so on, in lowercase.

Syntax:
router.METHOD(path, [callback, ...] callback)

Parameter: The path parameter speci昀椀es the path on the


URL and callback is the function that is executed when this
path is called.

Return Value: Since, it provides the routing functionality, so


it can return responses.

Installation of the express module:

You can visit the link to Install the express module. You can
install this package by using this command.

npm install express

After installing the express module, you can check your


express version in the command prompt using the command.

npm version express

After that, you can just create a folder and add a 昀椀le, for
example, index.js. To run this 昀椀le you need to run the
following command.

node index.js

Project Structure:

Example 1: Filename: index.js


 javascript

const express = require('express');

const app = express();

const router = express.Router();

const PORT = 3000;

// Single route

router.get('/user', function (req, res, next) {

console.log("GET request called");

res.end();

});

app.use(router);

app.listen(PORT, function (err) {

if (err) console.log(err);

console.log("Server listening on PORT", PORT);


});

Steps to run the program:

Make sure you have installed the express module using the
following command:

npm install express

Run the index.js 昀椀le using the below command:

node index.js

Output:

Console Output:

Server listening on PORT 3000

Now make a GET request to http://localhost:3000/, you can


see the following output on your screen:

Server listening on PORT 3000

GET request called

Example 2: Filename: index.js

 javascript

const express = require('express');


const app = express();

const router = express.Router();

const PORT = 3000;

// Multiple routes

router.get('/user', function (req, res, next) {

console.log("GET request called");

res.end();

});

router.post('/user', function (req, res, next) {

console.log("POST request called");

res.end();

});

router.delete('/user', function (req, res, next) {

console.log("DELETE request called");


res.end();

})

app.use(router);

app.listen(PORT, function (err) {

if (err) console.log(err);

console.log("Server listening on PORT", PORT);

});

Steps to run the program:

Run the index.js 昀椀le using the below command:

node index.js

Output:

Now make GET, POST, and DELETE request to


http://localhost:3000/, you can see the following output on
your screen:

Server listening on PORT 3000

GET request called


POST request called

DELETE request called

eactJS Virtual DOM


10Nov, 2023

React JS Virtual DOM is an in-memory representation of the


DOM. DOM refers to the Document Object Model that
represents the content of XML or HTML documents as a tree
structure so that the programs can be read, accessed and
changed in the document structure, style, and content.
Table of Content

 Prerequisites

 What is DOM ?

 Disadvantages of real DOM


 Virtual DOM

 How does virtual DOM actually make things faster?

 How virtual DOM Helps React?

 Virtual DOM Key Concepts

 Di昀昀erences between Virtual DOM and Real DOM


What is DOM ?
DOM stands for ‘Document Object Model’. In simple terms, it
is a structured representation of the HTML elements that are
present in a webpage or web app. DOM represents the entire
UI of your application. The DOM is represented as a tree data
structure. It contains a node for each UI element present in
the web document. It is very useful as it allows web
developers to modify content through JavaScript, also it being
in structured format helps a lot as we can choose speci昀椀c
targets and all the code becomes much easier to work with.
Disadvantages of real DOM :
Every time the DOM gets updated, the updated element and
its children have to be rendered again to update the UI of our
page. For this, each time there is a component update, the
DOM needs to be updated and the UI components have to be
re-rendered.
Example:

// Simple getElementById() method


document.getElementById('some-id').innerValue = 'updated
value';
When writing the above code in the console or in the
JavaScript 昀椀le, these things happen:

The browser parses the HTML to 昀椀nd the node with this id.

It removes the child element of this speci昀椀c element.


Updates the element(DOM) with the ‘updated value’.

Recalculates the CSS for the parent and child nodes.

Update the layout.

Finally, traverse the tree and paint it on the


screen(browser) display.
Recalculating the CSS and changing the layouts involves
complex algorithms, and they do a昀昀ect the performance. So
React has a di昀昀erent approach to dealing with this, as it
makes use of something known as Virtual DOM.
Virtual DOM
React uses Virtual DOM exists which is like a lightweight copy
of the actual DOM(a virtual representation of the DOM). So
for every object that exists in the original DOM, there is an
object for that in React Virtual DOM. It is exactly the same,
but it does not have the power to directly change the layout
of the document.
Manipulating DOM is slow, but manipulating Virtual
DOM is fast as nothing gets drawn on the screen. So each
time there is a change in the state of our application, the
virtual DOM gets updated 昀椀rst instead of the real DOM.
How does virtual DOM actually make
things faster?
When anything new is added to the application, a virtual DOM
is created and it is represented as a tree. Each element in the
application is a node in this tree. So, whenever there is a
change in the state of any element, a new Virtual DOM tree is
created. This new Virtual DOM tree is then compared with the
previous Virtual DOM tree and make a note of the changes.
After this, it 昀椀nds the best possible ways to make these
changes to the real DOM. Now only the updated elements will
get rendered on the page again.
How virtual DOM Helps React?
In React, everything is treated as a component be it a
functional component or class component. A component can
contain a state. Whenever the state of any component is
changed react updates its Virtual DOM tree. Though it may
sound like it is ine昀昀ective the cost is not much signi昀椀cant as
updating the virtual DOM doesn’t take much time.
React maintains two Virtual DOM at each time, one contains
the updated Virtual DOM and one which is just the pre-update
version of this updated Virtual DOM. Now it compares the
pre-update version with the updated Virtual DOM and 昀椀gures
out what exactly has changed in the DOM like which
components have been changed. This process of comparing
the current Virtual DOM tree with the previous one is known
as ‘di昀케ng’. Once React 昀椀nds out what exactly has changed
then it updates those objects only, on real DOM.
React uses something called batch updates to update the
real DOM. It just means that the changes to the real DOM are
sent in batches instead of sending any update for a single
change in the state of a component.
We have seen that the re-rendering of the UI is the most
expensive part and React manages to do this most e昀케ciently
by ensuring that the Real DOM receives batch updates to re-
render the UI. This entire process of transforming changes to
the real DOM is called Reconciliation.
This signi昀椀cantly improves the performance and is the main
reason why React and its Virtual DOM are much loved by
developers all around.
The diagrammatic image below brie昀氀y describes how the
virtual DOM works in the real browser environment

Real DOM to Virtual DOM


Virtual DOM Key Concepts :
Virtual DOM is the virtual representation of Real DOM

React update the state changes in Virtual DOM 昀椀rst and


then it syncs with Real DOM

Virtual DOM is just like a blueprint of a machine, can do


changes in the blueprint but those changes will not directly
apply to the machine.

Virtual DOM is a programming concept where a virtual


representation of a UI is kept in memory synced with “Real
DOM ” by a library such as ReactDOM and this process is
called reconciliation

Virtual DOM makes the performance faster, not because


the processing itself is done in less time. The reason is the
amount of changed information – rather than wasting time
on updating the entire page, you can dissect it into small
elements and interactions
Di昀昀erences between Virtual DOM and
Real DOM
Virtual DOM Real DOM

It is a tree representa琀椀on of HTML


It is a lightweight copy of the original DOM
elements

It is maintained by the browser a昀琀er


It is maintained by JavaScript libraries
parsing HTML elements
A昀琀er manipula琀椀on it only re-renders A昀琀er manipula琀椀on, it re-render the en琀椀re
changed elements DOM

Updates are lightweight Updates are heavyweight

Performance is slow and the UX quality is


Performance is fast and UX is op琀椀mised
low

Highly e昀케cient as it performs batch Less e昀케cient due to re-rendering of DOM


updates a昀琀er each update

Cloud Deployment Models


11, 2023

Pre-Requisite: Cloud Computing


In cloud computing, we have access to a shared pool of
computer resources (servers, storage, programs, and so on)
in the cloud. You simply need to request additional resources
when you require them. Getting resources up and running
quickly is a breeze thanks to the clouds. It is possible to
release resources that are no longer necessary. This method
allows you to just pay for what you use. Your cloud provider is
in charge of all upkeep.

What is a Cloud Deployment Model?


Cloud Deployment Model functions as a virtual computing
environment with a deployment architecture that varies
depending on the amount of data you want to store and who
has access to the infrastructure.

Types of Cloud Computing Deployment


Models
The cloud deployment model identi昀椀es the speci昀椀c type of
cloud environment based on ownership, scale, and access, as
well as the cloud’s nature and purpose. The location of the
servers you’re utilizing and who controls them are de昀椀ned by
a cloud deployment model. It speci昀椀es how your cloud
infrastructure will look, what you can change, and whether
you will be given services or will have to create everything
yourself. Relationships between the infrastructure and your
users are also de昀椀ned by cloud deployment types. Di昀昀erent
types of cloud computing deployment models are described
below.

 Public Cloud

 Private Cloud
 Hybrid Cloud

 Community Cloud

 Multi-Cloud
Public Cloud
The public cloud makes it possible for anybody to access
systems and services. The public cloud may be less secure as
it is open to everyone. The public cloud is one in which cloud
infrastructure services are provided over the internet to the
general people or major industry groups. The infrastructure in
this cloud model is owned by the entity that delivers the
cloud services, not by the consumer. It is a type of cloud
hosting that allows customers and users to easily access
systems and services. This form of cloud computing is an
excellent example of cloud hosting, in which service
providers supply services to a variety of customers. In this
arrangement, storage backup and retrieval services are given
for free, as a subscription, or on a per-user basis. For
example, Google App Engine etc.

Public Cloud
Advantages of the Public Cloud Model

 Minimal Investment: Because it is a pay-per-use service,


there is no substantial upfront fee, making it excellent for
enterprises that require immediate access to resources.

 No setup cost: The entire infrastructure is fully


subsidized by the cloud service providers, thus there is no
need to set up any hardware.

 Infrastructure Management is not required: Using the


public cloud does not necessitate infrastructure
management.

 No maintenance: The maintenance work is done by the


service provider (not users).

 Dynamic Scalability: To ful昀椀ll your company’s needs, on-


demand resources are accessible.
Disadvantages of the Public Cloud Model

 Less secure: Public cloud is less secure as resources are


public so there is no guarantee of high-level security.

 Low customization: It is accessed by many public so it


can’t be customized according to personal requirements.
Private Cloud
The private cloud deployment model is the exact opposite of
the public cloud deployment model. It’s a one-on-one
environment for a single user (customer). There is no need to
share your hardware with anyone else. The distinction
between private and public clouds is in how you handle all of
the hardware. It is also called the “internal cloud” & it refers
to the ability to access systems and services within a given
border or organization. The cloud platform is implemented in
a cloud-based secure environment that is protected by
powerful 昀椀rewalls and under the supervision of an
organization’s IT department. The private cloud gives greater
昀氀exibility of control over cloud resources.

Private Cloud

Advantages of the Private Cloud Model

 Better Control: You are the sole owner of the property.


You gain complete command over service integration, IT
operations, policies, and user behavior.

 Data Security and Privacy: It’s suitable for storing


corporate information to which only authorized sta昀昀 have
access. By segmenting resources within the same
infrastructure, improved access and security can be
achieved.

 Supports Legacy Systems: This approach is designed to


work with legacy systems that are unable to access the
public cloud.
 Customization: Unlike a public cloud deployment, a
private cloud allows a company to tailor its solution to
meet its speci昀椀c needs.
Disadvantages of the Private Cloud Model

 Less scalable: Private clouds are scaled within a certain


range as there is less number of clients.

 Costly: Private clouds are more costly as they provide


personalized facilities.
Hybrid Cloud
By bridging the public and private worlds with a layer of
proprietary software, hybrid cloud computing gives the best
of both worlds. With a hybrid solution, you may host the app
in a safe environment while taking advantage of the public
cloud’s cost savings. Organizations can move data and
applications between di昀昀erent clouds using a combination of
two or more cloud deployment methods, depending on their
needs.

Hybrid Cloud
Advantages of the Hybrid Cloud Model

 Flexibility and control: Businesses with more 昀氀exibility


can design personalized solutions that meet their
particular needs.

 Cost: Because public clouds provide scalability, you’ll only


be responsible for paying for the extra capacity if you
require it.

 Security: Because data is properly separated, the


chances of data theft by attackers are considerably
reduced.
Disadvantages of the Hybrid Cloud Model

 Di昀케cult to manage: Hybrid clouds are di昀케cult to


manage as it is a combination of both public and private
cloud. So, it is complex.

 Slow data transmission: Data transmission in the hybrid


cloud takes place through the public cloud so latency
occurs.
Community Cloud
It allows systems and services to be accessible by a group of
organizations. It is a distributed system that is created by
integrating the services of di昀昀erent clouds to address the
speci昀椀c needs of a community, industry, or business. The
infrastructure of the community could be shared between the
organization which has shared concerns or tasks. It is
generally managed by a third party or by the combination of
one or more organizations in the community.
Community Cloud

Advantages of the Community Cloud Model

 Cost E昀昀ective: It is cost-e昀昀ective because the cloud is


shared by multiple organizations or communities.

 Security: Community cloud provides better security.

 Shared resources: It allows you to share resources,


infrastructure, etc. with multiple organizations.

 Collaboration and data sharing: It is suitable for both


collaboration and data sharing.
Disadvantages of the Community Cloud Model

 Limited Scalability: Community cloud is relatively less


scalable as many organizations share the same resources
according to their collaborative interests.

 Rigid in customization: As the data and resources are


shared among di昀昀erent organizations according to their
mutual interests if an organization wants some changes
according to their needs they cannot do so because it will
have an impact on other organizations.
Multi-Cloud
We’re talking about employing multiple cloud providers at the
same time under this paradigm, as the name implies. It’s
similar to the hybrid cloud deployment approach, which
combines public and private cloud resources. Instead of
merging private and public clouds, multi-cloud uses many
public clouds. Although public cloud providers provide
numerous tools to improve the reliability of their services,
mishaps still occur. It’s quite rare that two distinct clouds
would have an incident at the same moment. As a result,
multi-cloud deployment improves the high availability of your
services even more.
Multi-Cloud

Advantages of the Multi-Cloud Model

 You can mix and match the best features of each cloud
provider’s services to suit the demands of your apps,
workloads, and business by choosing di昀昀erent cloud
providers.
 Reduced Latency: To reduce latency and improve user
experience, you can choose cloud regions and zones that
are close to your clients.

 High availability of service: It’s quite rare that two


distinct clouds would have an incident at the same
moment. So, the multi-cloud deployment improves the
high availability of your services.
Disadvantages of the Multi-Cloud Model

 Complex: The combination of many clouds makes the


system complex and bottlenecks may occur.

 Security issue: Due to the complex structure, there may


be loopholes to which a hacker can take advantage hence,
makes the data insecure.
What is the Right Choice for Cloud
Deployment Model?
As of now, no such approach 昀椀ts picking a cloud deployment
model. We will always consider the best cloud deployment
model as per our requirements. Here are some factors which
should be considered before choosing the best deployment
model.

 Cost: Cost is an important factor for the cloud deployment


model as it tells how much amount you want to pay for
these things.

 Scalability: Scalability tells about the current activity status


and how much we can scale it.

 Easy to use: It tells how much your resources are trained


and how easily can you manage these models.
 Compliance: Compliance tells about the laws and
regulations which impact the implementation of the model.

 Privacy: Privacy tells about what data you gather for the
model.
Each model has some advantages and some disadvantages,
and the selection of the best is only done on the basis of your
requirement. If your requirement changes, you can switch to
any other model.

Overall Analysis of Cloud Deployment


Models
The overall Analysis of these models with respect to di昀昀erent
factors is described below.

Public Community
Factors Cloud Private Cloud Cloud Hybrid Cloud

Complex, Complex, Complex,


requires a requires a requires a
Ini琀椀al Setup Easy
professional professional professional
team to setup team to setup team to setup

Scalability
High High Fixed High
and Flexibility

Cost- Cost- Distributed cost Between public


Costly
Comparison E昀昀ec琀椀ve among members and private cloud

Reliability Low Low High High


Data Security Low High High High

Data Privacy Low High High High

React Components
12Apr, 2024


Components in React serve as independent and reusable
code blocks for UI elements. They represent di昀昀erent parts of
a web page and contain both structure and behavior. They
are similar to JavaScript functions and make creating and
managing complex user interfaces easier by breaking them
down into smaller, reusable pieces.
What are React Components?
React Components are the building block of React
Application. They are the reusable code blocks containing
logics and and UI elements. They have the same purpose as
JavaScript functions and return HTML. Components make
the task of building UI much easier.
A UI is broken down into multiple individual pieces called
components. You can work on components independently
and then merge them all into a parent component which
will be your 昀椀nal UI.
Components promote e昀케ciency and scalability in web
development by allowing developers to compose, combine,
and customize them as needed.
You can see in the below image we have broken down the UI
of GeeksforGeeks’s homepage into individual components.
Components in React return a piece of JSX code that tells
what should be rendered on the screen.
Types of Components in React
In React, we mainly have two types of components:

Functional Components

Class based Components


Functional Component in React
Functional components are just like JavaScript functions
that accept properties and return a React element.
We can create a functional component in React by writing a
JavaScript function. These functions may or may not receive
data as parameters, we will discuss this later in the tutorial.
The below example shows a valid functional component in
React:
Syntax:

function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Example: Create a function component called welcome.

Javascript

function welcome() {

return <h1>Hello, Welcome to GeeksforGeeks!</h1>;

}
Class Component in React
The class components are a little more complex than the
functional components. A class component can show
inheritance and access data of other components.
Class Component must include the line “extends
React.Component” to pass data from one class component
to another class component. We can use JavaScript ES6
classes to create class-based components in React.
Syntax:

class Democomponent extends React.Component {


render() {
return <h1>Welcome Message!</h1>;
}
}
The below example shows a valid class-based component in
React:
Example: Create a class component called welcome.

Javascript

class Welcome extends Component {

render() {

return <h1>Hello, Welcome to GeeksforGeeks!</h1>;

}
The components we created in the above two examples are
equivalent, and we also have stated the basic di昀昀erence
between a functional component and a class component. We
will learn about more properties of class-based components
in further tutorials.
Functional Component vs Class
Component
A functional component is best suited for cases where the
component doesn’t need to interact with other components
or manage complex states. Functional components are ideal
for presenting static UI elements or composing multiple
simple components together under a single parent
component.
While class-based components can achieve the same result,
they are generally less e昀케cient compared to functional
components. Therefore, it’s recommended to not use class
components for general use.
Rendering React Components
Rendering Components means turning your component
code into the UI that users see on the screen.
React is capable of rendering user-de昀椀ned components. To
render a component in React we can initialize an element
with a user-de昀椀ned component and pass this element as the
昀椀rst parameter to ReactDOM.render() or directly pass the
component as the 昀椀rst argument to the ReactDOM.render()
method.
The below syntax shows how to initialize a component to an
element:

const elementName = <ComponentName />;


In the above syntax, the ComponentName is the name of the
user-de昀椀ned component.
Note: The name of a component should always start with a
capital letter. This is done to di昀昀erentiate a component tag
from an HTML tag.
Example: This example renders a component named
Welcome to the Screen.

javascript

// Filename - src/index.js:

import React from "react";

import ReactDOM from "react-dom";

// This is a functional component


const Welcome = () => {

return <h1>Hello World!</h1>;

};

ReactDOM.render(

<Welcome />,

document.getElementById("root")

);
Output: This output will be visible on the
http://localhost:3000/ on the browser window.

Explanation:
Let us see step-wise what is happening in the above
example:

We call the ReactDOM.render() as the 昀椀rst parameter.

React then calls the component Welcome, which returns


<h1>Hello World!</h1>; as the result.

Then the ReactDOM e昀케ciently updates the DOM to match


with the returned element and renders that element to the
DOM element with id as “root”.
Props
Props(short for properties) are a way to pass data from
the parent component to the child component.
Props are like function arguments, you can use them as
attributes in components.
Example:

Javascript

function Message(props) {

return <h2>{props.text}</h2>;

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Message text="Hello, world!" />);


Components in Components
We can call components inside another component
Example:

Javascript

// Filename - src/index.js:

import React from "react";

import ReactDOM from "react-dom";

const Greet = () => {

return <h1>Hello Geek</h1>

// This is a functional component


const Welcome = () => {

return <Greet />;

};

ReactDOM.render(

<Welcome />,

document.getElementById("root")

);
The above code will give the same output as other examples
but here we have called the Greet component inside the
Welcome Component.

You might also like