Javascript
Javascript
3.a Write a JavaScript program to find the area of a circle using radius (var and let -
reassign and observe the difference with var and let) and PI (const)
Program
var radius = 5;
var pi = 3.14;
var area = pi * radius * radius;
console.log("The area of the circle is: " + area);
// Using let to declare variables (reassigning)
let newRadius = 8;
area = pi * newRadius * newRadius;
console.log("The area of the circle with new radius is: " + area);
OutPut:
3 b) Write JavaScript code to display the movie details such as movie name,
starring,
language, and ratings. Initialize the variables with values of appropriate types.
Use
template literals wherever necessary.
Program:-
// Initialize variables
const movieName = "The Godfather";
const starring = ["Marlon Brando", "Al Pacino", "James Caan"];
const language = "English";
const ratings = 9.2;
OutPut:
3.c)Write JavaScript code to book movie tickets online and calculate the total price,
considering the number of tickets and price per ticket as Rs. 150. Also, apply a festive
season discount of 10% and calculate the discounted amount
program:
// Initialize variables
const numTickets = 4;
const ticketPrice = 150;
const discountPercent = 10;
// Display results
console.log(`Number of tickets: ${numTickets}`);
console.log(`Ticket price: Rs. ${ticketPrice}`);
console.log(`Total price: Rs. ${totalPrice}`);
console.log(`Discount: ${discountPercent}%`);
console.log(`Discounted amount: Rs. ${discountAmount}`);
console.log(`Discounted price: Rs. ${discountedPrice}`);
OutPut:
Number of tickets: 4
Ticket price: Rs. 150
Total price: Rs. 600
Discount: 10%
Discounted amount: Rs. 60
Discounted price: Rs. 540
3.d Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost per
ticket remains Rs. 150. (b) If seats are 6 or more, booking is not allowed.
Program:
// Initialize variables
const numTickets = 4;
const ticketPrice = numTickets <= 2 ? 150 : numTickets >= 6 ? null : 200;
OutPut:
Number of tickets: 4
Ticket price: Rs. 200
Total price: Rs. 800
3 e) Types of Loops
Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost per
ticket remains Rs. 150. (b) If seats are 6 or more, booking is not allowed. (c) If
program:
// Initialize variables
const maxSeatsAllowed = 5;
const ticketPrice = 150;
let numTickets = 0;
// Display results
if (totalPrice > 0) {
console.log(`Number of tickets: ${numTickets}`);
console.log(`Ticket price: Rs. ${ticketPrice}`);
console.log(`Total price: Rs. ${totalPrice}`);
}
Javascript
Exercise-4
Program:
if (numSeats <= 2)
Else
let numSeatsToBook = 4;
console.log("Total price for " + numSeatsToBook + " seats: Rs. " + totalPrice);
4b) Module name: Working With Classes, Creating and Inheriting Classes
Create an Employee class extending from a base class Person. Hints: (i) Create a class
Person with name and age as attributes. (ii) Add a constructor to initialize the values
(iii) Create a class Employee extending Person with additional attributes role
Program:
// Java program to create an employee class
// by inheriting Person class
class Person
{
String name;
int age;
void printEmployeeDetails()
{
System.out.println("Employee ID : " + emp_id);
System.out.println("Employee Name : " + name);
System.out.println("Employee Age : " + age);
System.out.println("Employee Salary : " + emp_salary);
}
}
Output:
Employee ID : 101
Employee Name : Savas Akhtan
Employee Age : 32
Employee Salary : 22340
Program:
c onst coneStates =
{
empty:
{
heading: "Empty Cone",
message: "Oops, looks like you ate all the ice
cream!",
backgroundColor: "#FFC0CB",
coneFill: "empty",
},
filled:
{
heading: "Delicious Ice Cream Cone",
message: "Enjoy your treat!",
backgroundColor: "#ADD8E6",
coneFill: "filled",
},
};
Output: Delicious ice cream cone
Enjoy your taste
Green
Filled
Javascript
Exercise-5
5a)Module Name: Creating arrays,Destructing arrays,accessing arrays,array methods
Create an array of objects having movie details. The object should include the movie
name, starring, language, and ratings. Render the details of movies on the page using
the array
program:
const movies = [
{
name: "The Shawshank Redemption",
starring: ["Tim Robbins", "Morgan Freeman"],
language: "English",
ratings:
{
imdb: 9.3,
rottenTomatoes: 90,
metacritic: 80
}
},
{
name: "The Godfather",
starring: ["Marlon Brando", "Al Pacino"],
language: "English",
ratings:
{
imdb: 9.2,
rottenTomatoes: 98,
metacritic: 100
}
},
{
name: "The Dark Knight",
starring: ["Christian Bale", "Heath Ledger"],
language: "English",
ratings:
{
imdb: 9.0,
rottenTomatoes: 94,
metacritic: 84
}
},
{
name: "Parasite",
starring: ["Song Kang-ho", "Lee Sun-kyun", "Cho Yeo-jeong"],
language: "Korean",
ratings:
{
imdb: 8.6,
rottenTomatoes: 99,
metacritic: 96
}
}
];
Output:
Validate the user by creating a login module. Hints: (i) Create a file login.js with a
User class. (ii) Create a validate method with username and password as arguments.
(iii) If the username and password are equal it will return "Login Successful" else w
Program:
// login.js
class User
{
constructor(username, password)
{
this.username = username;
this.password = password;
}
validate(username, password)
{
if (username === this.username && password === this.password)
{
return "Login Successful";
} else
{
return "Invalid username or password";
}
}
}
Output:
Username:shiva
Password:shiva@1234
Node.js
Exercise-6
Node.js is a runtime environment that allows you to run JavaScript code outside of a web
browser, typically on a server. Here's an overview of how to use Node.js and execute
functions within it:
1. Install Node.js: To get started with Node.js, you'll need to install it on your
computer. You can download the installer for your operating system from the
Node.js website: https://nodejs.org/en/download/. Follow the installation
instructions to install Node.js on your computer.
2. Create a JavaScript file: Once you have Node.js installed, create a new file with a .js
extension and write some JavaScript code in it. For example, you could create a file
called hello.js with the following code:
javascript
console.log("Hello, world!");
3. Run the JavaScript file with Node.js: To execute the JavaScript file with Node.js, open
a terminal or command prompt, navigate to the directory where the hello.js file is
located, and run the following command:
bash
node hello.js
This will run the hello.js file with Node.js and output "Hello, world!" to the console.
4. Use Node.js modules: Node.js has a built-in module system that allows you to use
external libraries in your JavaScript code. To use a module, you can use the
require() function to import it into your code. For example, if you wanted to use
the fs module to read and write files, you could modify your hello.js file like this:
javascript
const fs = require("fs");
This code imports the fs module, which provides functions for working with the file
system. It then uses the writeFile() function to write the string "Hello, world!" to a file
called output.txt. The function takes a callback function that is called when the write
operation is complete.
if (args.length > 0)
{
console.log(`Hello, ${args[0]}!`);
} else
{
console.log("Hello, world!");
}
This code uses the process.argv array to get the command-line arguments passed to the
script, slices off the first two arguments (which are the node binary and the name of the
script), and checks if any arguments were provided. If an argument was provided, it
outputs a custom greeting with the argument value; otherwise, it outputs the default
"Hello, world!" message.
These are just a few examples of how to use Node.js and execute functions within it. Node.js
provides a wide range of built-in modules and external libraries that you can use to build a
wide range of applications, from simple command-line tools to complex web applications.
6b)Create a web server in Node.js Write a program to show the workflow of JavaScript code
executable by creating web server in Node.js.
const http = require('http');
server.listen(port, ()
{
console.log(`Server running at http://localhost:${port}/`);
});
Output: Server running at http://localhost:3000/
Program:
exports.add = function(a, b)
{
return a + b;
};
exports.subtract = function(a, b)
{
return a - b;
};
exports.multiply = function(a, b)
{
return a * b;
};
exports.divide = function(a, b)
{
if (b === 0)
{
throw new Error('Cannot divide by zero');
}
return a / b;
};
const calculator = require('./calculator');
const a = 10;
const b = 5;
Express.js
Exercise-7
In myNotes application: (i) we want to handle POST submissions. (ii) display customized error
messages. (iii) perform logging.
Middleware is software that acts as a bridge between different components of an
application or system. It typically sits between the client and server, intercepting requests
and responses, and adding additional functionality to the application's core logic. In the
context of a web application, middleware can be used to handle tasks such as parsing
request data, authenticating users, logging, and error handling.
In the case of your myNotes application, you have identified three tasks that can be
accomplished using middleware: handling POST submissions, displaying customized error
messages, and performing logging. Here's how each of these tasks can be accomplished
using middleware:
Types of Middlewares: There are several types of middleware that can be used in web
applications.
4.Built-in middleware: Some web frameworks come with built-in middleware that
provides common functionality, such as parsing request data or serving static files.
7b) Module Name: Models
Program:
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
age: Number
});
// Create a model based on the schema
User.create({
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
age: 30
})
.then((result) => {
})
.catch((error) => {
});
id: 61eb23c67d7ccfd8e3870812,
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
age: 30,
}
Express.js
Exercise-8
program:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true });
// Create operation
async function createData()
{
const data = new MyModel
({
name: 'John Doe',
age: 30,
email: '[email protected]'
});
await data.save();
console.log('Data created:', data);
}
console.log('\nRetrieving data...');
await readData();
console.log('\nUpdating data...');
await updateData('606d7eb765808c2a90ebcf6c', { name: 'Jane Doe' });
console.log('\nDeleting data...');
await deleteData('606d7eb765808c2a90ebcf6c');
Retrieving data...
Data retrieved: [ { _id: 606d7eb765808c2a90ebcf6c, name: 'John Doe', age: 30, email:
'[email protected]', __v: 0 } ]
Updating data...
Data updated: { _id: 606d7eb765808c2a90ebcf6c, name: 'Jane Doe', age: 30, email:
'[email protected]', __v: 0 }
Deleting data...
Data deleted: { _id:
8b)Module Name:Sessions
Write a program to explain session management using sessions.
Program:
{
"username": "user",
"password": "password"
}
You are now logged in.
Helmet is a middleware package for Node.js that helps secure your application by setting
various HTTP headers to prevent attacks like cross-site scripting (XSS), clickjacking, and
cross-site request forgery (CSRF).
To implement Helmet middleware in your myNotes application, you can follow these steps:
1. Install the Helmet package by running the following command in your terminal:
javascript
const helmet = require('helmet');
app.use(helmet());
This will set various HTTP headers to improve the security of your application, including:
Typescript
Exercise-9
On the page, display the price of the mobile-based in three different colors. Instead of
using the number in our code, represent them by string values like Gold Platinum, Pink
Gold, Silver Titanium.
Now, coming to your question, to display the price of a mobile in three different colors, we
can create a variable price and assign it a string value representing the color of the
mobile.
Program:
Output:
Assuming you have an array of products and an event handler function that receives a
productId parameter, here's how you can define an arrow function inside the event
handler to filter the product array and pass the selected product object to the next screen
in TypeScript:
const products = [
];
Output:
Product1: Mobile
Price:3000
Product 2: Watch
Price: 1000
Price: 1500
interface Mobile
name: string;
vendor: string;
];
Output:
Exercise-10
Implement business logic for adding multiple Product values into a cart variable which is
type of string array.
Program:
void
cart.push(product);
addToCart("Product 1");
addToCart("Product 2");
addToCart("Product 3");
Output:
Declare an interface named - Product with two properties like productId and
productName with a number and string datatype and need to implement logic to populate
the Product details .
Program:
interface Product
productId: number;
productName: string;
productId: 1234,
};
10c)Duck Typing
Declare an interface named - Product with two properties like productId and
productName with the number and string datatype and need to implement logic to
populate the Product details.
Program:interface Product
productId: number;
productName: string;
}
productId: 123,
};