KEMBAR78
Node JS | PDF | Java Script | Callback (Computer Programming)
0% found this document useful (0 votes)
20 views19 pages

Node JS

Node.js is an open-source JavaScript runtime environment that enables running JavaScript code outside of a browser, featuring asynchronous, event-driven architecture and a package manager called NPM. It includes various components like modules, streams, and the ability to handle HTTP requests, along with tools for database connections and file operations. The document also covers creating local modules, using Express.js for web applications, and differences between HTTP methods.

Uploaded by

samarthsupekar15
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)
20 views19 pages

Node JS

Node.js is an open-source JavaScript runtime environment that enables running JavaScript code outside of a browser, featuring asynchronous, event-driven architecture and a package manager called NPM. It includes various components like modules, streams, and the ability to handle HTTP requests, along with tools for database connections and file operations. The document also covers creating local modules, using Express.js for web applications, and differences between HTTP methods.

Uploaded by

samarthsupekar15
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/ 19

NODE JD IMP

1.What is NodeJS?

Node.js is an open-source, cross-platform JavaScript runtime environment that allows you to run
JavaScript code outside of a web browser — typically on a server.

Main Features of Node.js:

• Asynchronous and Event-Driven: Handles multiple operations without waiting for any to
complete.

• Fast Execution: Thanks to the V8 engine.

• Single-Threaded but Highly Scalable: It uses a single thread to handle many connections
efficiently.

• NPM (Node Package Manager): A vast collection of reusable packages (libraries).

2.What are the components of NPM?

i. Website (npmjs.com)

• The NPM website is where developers can browse and search for open-source Node.js
packages.

ii. Command Line Interface (CLI)

• When you install Node.js, it also installs the npm command-line tool.

• Install, update, publish, and manage packages from terminal

iii. NPM Registry

• The Registry is a large database (or storage) where all the packages (and their versions) are
hosted.

• Database that stores all packages and metadata.

3.Write the syntax to read a line asynchronously in Node.js using the fs module.

• fs.readFile() is asynchronous — it reads the file without blocking the program.


• 'utf8' ensures that the file is read as a string rather than a buffer.
• err will contain error information (if any), and data will have the file content.

Syntax:-

const fs = require('fs');

fs.readFile('filename.txt', 'utf8', (err, data) => {

if (err) {

console.error(err);

return;

console.log(data);
NODE JD IMP

});

4. Explain the syntax for configuring a database connection in a Node.js application.

In a Node.js application, configuring a database connection means setting up the code to connect
your app to a database (like MySQL, MongoDB, PostgreSQL, etc.).

The basic syntax usually follows this structure:

1. Import the database client module.

2. Create a connection with proper credentials (host, user, password, database name, etc.).

3. Connect to the database and handle success or error.

5. Define Anonymous function.

An anonymous function is a function without a name.

In JavaScript (and Node.js), anonymous functions are often used when you need a function as a
value — for example, as a callback, inside an event handler, or passed to another function.

Syntax:-

function () {

// function body

6.What are the features of Node Js ?

Features of Node.js:

• Asynchronous and Event-Driven: Handles multiple operations without waiting for any to
complete.

• Fast Execution: Thanks to the V8 engine.

• Single-Threaded but Highly Scalable: It uses a single thread to handle many connections
efficiently..

• NPM (Node Package Manager): A vast collection of reusable packages (libraries).

7. Explain global packages from Nodejs.

A global package is a Node module installed globally on your system rather than locally in a specific
project.

Command:- npm install -g package-name

8. What is express.js?

Express.js (or just Express) is a minimal and flexible Node.js web application framework that makes
it easy to build web servers and APIs quickly.

Express.js provides a set of tools and functions to make it easier to handle:

• Routing (handling different URLs)


NODE JD IMP

• HTTP Requests (GET, POST, PUT, DELETE)

9. Write syntax to create Buffer?

A Buffer is used to handle binary data directly — especially useful when dealing with files, network
packets, or streams.

Syntax:-

Buffer.alloc(size[, fill[, encoding]])

10.What is the use of prompt-Sync Sync module?

The prompt-sync module in Node.js is used for taking user input in the terminal or console. It
provides a way to interact with the user by displaying a prompt and waiting for them to enter text,
which can then be used in the program.

prompt-sync helps by providing an easy, synchronous way to prompt the user for input.

Syntax:-

npm install prompt-sync

11. Write about arrow function.

An arrow function is a concise way to write functions in JavaScript. It uses the => syntax, which
makes it shorter and often more readable.

Syntax:-

const function Name = (parameter1, parameter2) => {

// function body

12. What are the types of streams in NodeJs ?

streams are powerful tools for handling I/O operations (like reading and writing files, interacting
with networks, etc.) efficiently, without loading all data into memory at once.

There are four main types of streams in Node.js:

1. Readable Used to read data from a source. Reading files, receiving HTTP responses.

2. Writable Used to write data to a destination. Writing files, sending data over HTTP.

3. Duplex Can both read and write data. Network sockets, bidirectional streams.

4. Transform A special type of duplex stream where data is modified as it is read and written.

13.What is a module? List its types.

A module is essentially a file containing JavaScript code that can be required (imported) and used in
other parts of the program.
NODE JD IMP

Each module in Node.js has its own scope (i.e., the variables, functions, and objects inside it are not
shared with other modules unless explicitly exported).

Built-in, no installation required,


Core Modules http, fs, path, os, events
provided by Node.js.

Third-Party
External modules installed from npm. express, lodash, mongoose, axios
Modules

User-created modules to structure your Any JavaScript file with module.exports


Custom Modules
own code. or exports

14. What is the Command to intialize Node Package Manager (NPM)? Write it's syntax.

initialize Node Package Manager (NPM) in a Node.js project, you use the npm init command. This
command creates a package.json file, which contains metadata about your project, like its name,
version, description, dependencies, and scripts.

Syntax:-

npm init

15.What is REPL?

REPL stands for Read-Eval-Print Loop, and it's an interactive programming environment where you
can enter expressions and get immediate results.

1. Read: The REPL takes the user input (JavaScript expressions or code).

2. Eval: It evaluates the input expression and runs the code.

3. Print: It then prints the result of the evaluation back to the console.

4. Loop: The REPL continues to loop, allowing you to input more expressions.

16.List any four core modules of node.JS

i. http

• Used to create HTTP servers and handle HTTP requests and responses.

ii. fs (File System)

• Provides API to interact with the file system, such as reading, writing, and deleting files.

iii. path

• Used to handle and transform file paths (e.g., joining paths, resolving relative paths).

iv. os (Operating System)

• Provides information about the operating system, like platform, CPU architecture, and
network interfaces.
NODE JD IMP

17. Which directive is used to import node.JS modules?

require() loads the module, returns its exports (whatever the module has exported for use), and
allows you to interact with its functionality.

For local modules, you need to provide the relative path (e.g., './myModule').

18. List any 4 methods included under path module of node.JS?

path.join() Joins multiple path segments into a single path 'folder/subfolder/file.txt'

path.resolve() Resolves paths into an absolute path /home/user/project/folder/file.txt

path.extname() Returns the file extension of a given path .txt

path.basename() Returns the last portion of a path (usually the file name) file.txt

19. which tasks a file system module is used for?

Reading Files Read file content (sync or async).

Writing Files Write data to a file (sync or async).

Appending Data Add data to an existing file without overwriting it.

Deleting Files Remove files from the file system.

20. Write a command to add dependency "express" using NPM.

The "express" dependency to your Node.js project using npm.

npm install express

Install the express package and add it to your node_modules folder.

Add express as a dependency in your package.json file under the "dependencies" section.

21. which situation node. JS is not recomended to use?

While Node.js is a great choice for many types of applications, there are certain situations where it
might not be the best choice. Here are some scenarios where Node.js may not be recommended:

CPU-intensive tasks (complex calculations, large-scale data processing)

Complex multi-threading applications

Low-latency systems (e.g., high-frequency trading)

Traditional desktop apps

22.Write steps to handle http requests while creating web server using node.JS?

To handle HTTP requests while creating a web server in Node.js, you can use the built-in http
module. Here's how you can handle HTTP requests step by step:

Import the HTTP module


NODE JD IMP

Create a server instance: Use the http.createServer() method to create a new server object.

Handle Incoming Requests

Inside the callback function, you can check for the HTTP method (e.g., GET, POST) and URL path to
handle different requests accordingly.

Send HTTP Response

To send a response to the client, you can:

• Set status code using res.writeHead(statusCode).

Q 2. (4x4).

1. How we can create a local module with example.

Creating a local module in Node.js allows you to organize your code into reusable components,
making it more modular and maintainable. You can create a local module by defining a JavaScript file
with a set of functions or objects, and then exporting them for use in other files.

Steps to Create a Local Module in Node.js:

1. Create a JavaScript file for the module.

2. Export the functionality that you want to make available to other files.

3. Require the module in another file where you want to use the functionality.

Example:-

function add(a, b) {

return a + b;

function subtract(a, b) {

return a - b;

module.exports = {

add,

subtract

};

2. Explain module exports in Nodejs. With example ?

Module.exports is a special object used to export functionality from a module so that it can be used
in other files. When you write a Node.js module, you can export functions, objects, arrays, or even
classes using module.exports. This allows other files to import and use the code you’ve written in
the module.

module.exports = function(name) {

console.log('Hello, ' + name + '!');


NODE JD IMP

};

3.What is package.json File?

The package.json file is a crucial file in any Node.js project. It serves as the manifest for the project,
containing metadata and configurations about the project, its dependencies, scripts, and other
important information. The package.json file helps manage and automate many aspects of Node.js
projects.

npm init -y

4. Write steps to load core modules in Nodejs?

core modules are built-in libraries that provide essential functionality, such as handling files, HTTP
requests, streams, and more. These modules come pre-installed with Node.js, so you don’t need to
install them separately.

To load and use a core module, you simply use the require() function.

Step:-

Use the require() Function:

• Core modules are loaded using the require() function in Node.js.

Syntax to Load Core Modules:

• const moduleName = require('moduleName');

Use the Required Module:

• Once the core module is loaded, you can use its functionalities in your application.

5. How to write synchronous data to File explain with suitable example.

fs (File System) module provides APIs to interact with the file system. To write data synchronously to
a file, we can use the fs.writeFileSync() method. This method is part of the fs module and allows you
to write data to a file in a synchronous manner, meaning that it will block the execution of the
program until the file is written.

Syntax:- fs.writeFileSync():

const fs = require('fs');

const data = 'Hello, this is some text data written to the file synchronously!';

const filePath = './output.txt';

try {

fs.writeFileSync(filePath, data);

console.log('Data has been written to the file successfully!');

} catch (err) {

console.error('Error writing to the file:', err);

}
NODE JD IMP

6. Write a code for selecting all records from the "employee" table.

const mysql = require('mysql2');

const connection = mysql.createConnection({

host: 'localhost', // Database host (e.g., 'localhost')

user: 'root', // Database username

password: '', // Database password

database: 'your_database_name' // The name of your database

});

connection.connect((err) => {

if (err) {

console.error('Error connecting to the database:', err.stack);

return;

console.log('Connected to the database as id ' + connection.threadId);

});

const query = 'SELECT * FROM employee';

connection.query(query, (err, results) => {

if (err) {

console.error('Error executing query:', err.stack);

return;

console.log('Employee Records:', results);

});

connection.end();

7.Using Nodejs create a webpage to read two file Name from user and combine in third file.

App.js

const express = require('express');

const fs = require('fs');

const path = require('path');

const bodyParser = require('body-parser');


NODE JD IMP

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {

res.sendFile(path.join(__dirname, 'public', 'index.html'));

});

app.post('/combine', (req, res) => {

const { file1, file2, outputFile } = req.body;

const filePath1 = path.join(__dirname, file1);

const filePath2 = path.join(__dirname, file2);

if (!fs.existsSync(filePath1) || !fs.existsSync(filePath2)) {

return res.send('One or both of the files do not exist.');

const content1 = fs.readFileSync(filePath1, 'utf8');

const content2 = fs.readFileSync(filePath2, 'utf8');

const combinedContent = content1 + '\n' + content2;

const outputFilePath = path.join(__dirname, outputFile);

fs.writeFileSync(outputFilePath, combinedContent, 'utf8');

res.send(`Files combined successfully. The result is saved in ${outputFile}`);

});

const port = 3000;

app.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);

});

Index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


NODE JD IMP

<title>Combine Files</title>

</head>

<body>

<h1>Combine Two Files into a Third File</h1>

<form action="/combine" method="POST">

<label for="file1">Enter the first file name:</label><br>

<input type="text" id="file1" name="file1" required><br><br>

<label for="file2">Enter the second file name:</label><br>

<input type="text" id="file2" name="file2" required><br><br>

<label for="outputFile">Enter the output file name:</label><br>

<input type="text" id="outputFile" name="outputFile" required><br><br>

<input type="submit" value="Combine Files">

</form>

</body>

</html>

8.Write down the difference between GET and http request () method?

POST/PUT/DELETE/other HTTP request


Feature GET
methods

Retrieve data from the server Modify the server state (create, update,
Purpose
without modifying its state. delete).

Data Data is sent as query parameters in


Data is sent in the body of the request.
Transmission the URL.

Generally not cached (except in some


Cacheable Can be cached.
cases).

Yes (repeating GET requests yield the POST is not idempotent; PUT and DELETE
Idempotent
same result). are idempotent.

Less secure for sensitive data (data is


Security More secure (data is in the request body).
visible in the URL).

Limited by URL length (varies by No strict limits (depending on server


Data Length
browser). configurations).
NODE JD IMP

POST/PUT/DELETE/other HTTP request


Feature GET
methods

Can have side effects (creating, updating, or


Side Effects No side effects (just retrieving data).
deleting data).

9. Write Nodejs application find area a of rectangle & display the details defined Rectangle module
to on console.

class Rectangle {

constructor(length, width) {

this.length = length;

this.width = width;

getArea() {

return this.length * this.width;

displayDetails() {

console.log(`Rectangle Details:`);

console.log(`Length: ${this.length}`);

console.log(`Width: ${this.width}`);

console.log(`Area: ${this.getArea()}`);

module.exports = Rectangle;

10. What is web server?

A web server is a software or hardware system that serves web content (e.g., HTML, images, CSS,
JavaScript files, etc.) over the internet to a client (typically a web browser). The web server listens for
requests from clients, processes them, and returns the appropriate responses. The responses
typically consist of HTML content or other resources required by the client to display a webpage.

11. Explain parameters of create connection?

The createConnection() method takes a configuration object or parameters to establish the


connection. Here are the parameters commonly used to configure the connection:

const mysql = require('mysql2');


NODE JD IMP

// Create a connection to the database

const connection = mysql.createConnection({

host: 'localhost', // Host where the MySQL database is located

user: 'root', // The username to authenticate with the database

password: 'password', // The password for the user

database: 'test_db', // The name of the database to connect to

port: 3306, // The port number to connect to (default is 3306 for MySQL)

charset: 'utf8mb4', // Character set to use (optional)

timeout: 10000 // Timeout for the connection (optional, in milliseconds)

});

12.What are the advantages of nodes.JS?

Cross-Platform Development:

• Cross-Platform Compatibility: Node.js is cross-platform, which means you can develop


applications on Windows, Linux, and macOS without worrying about compatibility issues.

Easy to Learn:

• JavaScript Familiarity: For developers already familiar with JavaScript, learning Node.js is
easier since it uses JavaScript for both client-side and server-side programming.

Server-Side JavaScript:

• JavaScript on the Server: With Node.js, JavaScript can be used not only on the client side (in
the browser) but also on the server side. This allows for unified codebases and better
integration between the client and server.

Fast Development Cycle:

• Rapid Prototyping: Node.js supports a quick and fast development cycle, which allows
developers to build prototypes or production-ready applications in a short amount of time.

Real-time Data Processing:

• Real-time Applications: Node.js is ideal for real-time applications, such as online gaming,
collaboration tools, chat applications, and live streaming, where the server has to process
data continuously.

13.Write a program to update table records using node. JS and MYSQL database.

const mysql = require('mysql2');

const connection = mysql.createConnection({

host: 'localhost', // MySQL host

user: 'root', // MySQL username


NODE JD IMP

password: 'password', // MySQL password

database: 'test_db' // Database name

});

connection.connect((err) => {

if (err) {

console.error('Error connecting to the database:', err.stack);

return;

console.log('Connected to the database');

});

const updateQuery = `

UPDATE employees

SET name = ?, position = ?, salary = ?

WHERE id = ?

const updatedData = ['John Doe', 'Senior Developer', 75000, 1];

connection.query(updateQuery, updatedData, (err, results) => {

if (err) {

console.error('Error updating the record:', err.stack);

return;

console.log(`Record updated successfully. ${results.affectedRows} row(s) affected.`);

});

connection.end();

14. Explain node.JS process model with the help of diagram.

Node.js uses a single-threaded, event-driven architecture that is designed to handle asynchronous


I/O operations efficiently. The main strength of the Node.js process model is its ability to handle
many concurrent operations with minimal overhead. Here’s an explanation of how Node.js
processes requests using its event loop and non-blocking I/O.

15. How does node.JS handles a file request?

Receiving the File Request:


NODE JD IMP

• When a client (e.g., a browser or another application) sends an HTTP request to a Node.js
server to request a file (such as an image, HTML, CSS, or JSON file), Node.js accepts the
request through the HTTP module.

• The HTTP request may specify a file path that the server needs to return.

File Reading Using Non-blocking I/O:

• In Node.js, file reading operations (using the fs module) are non-blocking by default. This
means that when a file is requested, Node.js doesn’t wait for the file to be read before
continuing to handle other incoming requests.

• Asynchronous file reading is done by calling fs.readFile() or fs.createReadStream(). These


methods return immediately and perform the file reading operation in the background.

Example:-

const fs = require('fs');

const http = require('http');

const server = http.createServer((req, res) => {

const filePath = './path/to/your/file.txt'; // file requested by the client

fs.readFile(filePath, 'utf8', (err, data) => {

if (err) {

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

res.end('Error reading the file');

} else {

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

res.end(data); // Send the file data as response

});

});

server.listen(3000, () => {

console.log('Server is running on http://localhost:3000');

});

16. What is the purpose of object module.experts in node. JS?

Exporting Functions, Objects, or Values:

• By default, every Node.js module has a module.exports object. This object is what gets
returned when another file requires the module.
NODE JD IMP

• You can attach properties or functions to module.exports, and they will be available to the
file that imports the module.

Modularizing Code:

• module.exports is used to modularize and encapsulate functionality, which helps keep your
code clean and maintainable. You can separate different concerns (e.g., database
operations, utility functions) into different files and then combine them in your main
application.

Sharing Logic Between Files:

• Any file can require a module, and module.exports provides the specific exports (functions,
objects, variables) that the file can access. This allows you to reuse code across different
files.

17. Explain fs.readfile() method for all possible values of options?

The fs.readFile() method in Node.js is used to asynchronously read the contents of a file. It is part of
the fs (File System) module and allows you to read files in a non-blocking manner.

Syntax:- fs.readFile(path, options, callback)

path (String | Buffer | URL):

• The path to the file that you want to read. This can be a string representing the file path, a
buffer, or a URL.

options (Object | String):

• The options parameter can be either a string (encoding type) or an object that can include
multiple properties for customizing the behavior of the file reading operation.

callback (Function):

• This is a callback function that gets called after the file is read. The callback function takes
two arguments:

o err: An error object (if an error occurred during the read operation).

o data: The file content (Buffer or string, depending on the encoding).

18. Write a program which uses addlistener() method of Event Emmitter class.

const EventEmitter = require('events');

const myEmitter = new EventEmitter();

myEmitter.addListener('greet', (message) => {

console.log(`Greeting message: ${message}`);

});

myEmitter.emit('greet', 'Hello, Node.js!');

myEmitter.emit('greet', 'Welcome to the EventEmitter class!');


NODE JD IMP

19. Compare Traditional web server model and node.JS process model.

Feature Traditional Web Server Node.js Process Model

Concurrency
Multi-threaded, blocking I/O Single-threaded, non-blocking I/O
Handling

High scalability with lightweight event-


Scalability Limited by thread/process overhead
driven model

Can become slower with high I/O- Efficient for handling large numbers of
Performance
bound requests concurrent connections

Resource Low (due to single-threaded, non-


High (due to threads/processes)
Consumption blocking architecture)

Best for CPU-bound tasks, static content I/O-bound tasks, real-time applications

Example Apache, Nginx Node.js (using HTTP module)

20. Write a program to use SQL SELECT Qvery to show data from a table using node. JS and
MYSQLdata base.

const mysql = require('mysql');

const connection = mysql.createConnection({

host: 'localhost', // MySQL server hostname or IP address

user: 'root', // Your MySQL username

password: '', // Your MySQL password

database: 'testdb' // Your database name

});

connection.connect((err) => {

if (err) {

console.error('Error connecting to the database:', err.stack);

return;

console.log('Connected to the database as id ' + connection.threadId);

});

const sqlQuery = 'SELECT * FROM employees'; // Replace 'employees' with your table name

connection.query(sqlQuery, (err, results) => {

if (err) {

console.error('Error executing query:', err.stack);


NODE JD IMP

return;

console.log('Data from the "employees" table:');

console.log(results); // results will contain the rows returned by the query

});

connection.end((err) => {

if (err) {

console.error('Error closing the connection:', err.stack);

} else {

console.log('Database connection closed.');

});

21. Explain steps to install node. JS on windows.

Step 1: Download Node.js Installer

Step 2: Run the Node.js Installer

Step 3: Verify the Installation

Step 4: Update npm

Step 5: Test Node.js by Running a Simple Script

Step 6: Using Node.js with npm

22. Write a program to write to a file in node.JS.

const fs = require('fs');

const data = 'Hello, this is some text that will be written to the file!';

fs.writeFile('output.txt', data, (err) => {

if (err) {

console.error('Error writing to file:', err);

return;

console.log('Data has been written to the file successfully!');

});
NODE JD IMP

23. Explain path module.

The path module in Node.js provides utilities for working with file and directory paths. It allows you
to manipulate and interact with file paths in a way that is platform-independent (i.e., it handles
differences between Windows and UNIX-style file systems).

const path = require('path');

const fullPath = path.join('/users', 'john', 'documents', 'file.txt');

console.log(fullPath);

24. How to uninstall local package.

To uninstall a local package in Node.js (which is installed as a dependency in your project), you can
use the npm uninstall command.

npm uninstall <package-name>

25. How can we add Dependency in package.

To add a dependency in your Node.js project, you can use the npm install command. This will install
the package and also update your package.json file to include the package under dependencies.

Install a Package as a Dependency:

• npm install <package-name>

26. Write down the connection string of node.JS and MYSQL.

To connect a Node.js application to a MySQL database, you can use the mysql package. The
connection string generally includes the host, user, password, and database information

Steps to Install MySQL Package:-

• npm install mysql

27. Explain Event Driven Programming?

Event-driven programming (EDP) is a programming paradigm in which the flow of the program is
determined by events, such as user interactions, messages from other programs, or sensor outputs.
Instead of writing a linear sequence of instructions, an event-driven program is structured around
events that trigger specific actions or responses.

Core Concepts of Event-Driven Programming:

1. Event Emitters:

o An event-driven application typically involves event emitters that generate events.


These emitters can be objects, modules, or any part of the application that triggers
an event when certain conditions are met.

2. Event Listeners:

o Event listeners (also called handlers or callbacks) are functions that are executed in
response to specific events. They "listen" for events and run certain actions when
the event is triggered.
NODE JD IMP

3. Event Loop:

o The event loop is a mechanism that continuously checks for and processes events.
When an event is emitted, the event loop directs the corresponding event listener to
execute the code associated with it.

4. Callback Functions:

o Callbacks are functions that are passed as arguments to other functions or event
listeners. When an event occurs, the callback is called and executed.

5. Non-Blocking and Asynchronous:

o Event-driven programming is often associated with non-blocking behavior, where


the program doesn’t wait for a task to finish before moving on to the next one.
Instead, tasks are executed asynchronously, and callbacks are used to handle the
results when they’re ready.

28. Explain Anonymous function with an example.

An anonymous function is a function that is defined without a name. These functions are typically
used when a function is required temporarily or as a callback. In JavaScript, anonymous functions are
often used as callback functions and are commonly referred to as lambda functions or function
expressions.

Syntax:-

const functionName = function() {

// function body

};

Example:-

const greet = function() {

console.log("Hello, World!");

};

greet();

All The Best

You might also like