0% found this document useful (0 votes)
300 views25 pages

Javascript

Here are the key steps to execute functions in Node.js: 1. Install Node.js - Download and install the Node.js runtime from the official website. 2. Create a JavaScript file - Make a .js file containing your JavaScript code and functions. 3. Require modules (if needed) - Use require() to import external Node.js modules. 4. Define functions - Write function declarations to create reusable blocks of code. 5. Execute the file - Run the file using node command followed by the file name. Any functions will be executed. 6. See output - Check the terminal for any output or errors from your running functions. So in summary, Node.js
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)
300 views25 pages

Javascript

Here are the key steps to execute functions in Node.js: 1. Install Node.js - Download and install the Node.js runtime from the official website. 2. Create a JavaScript file - Make a .js file containing your JavaScript code and functions. 3. Require modules (if needed) - Use require() to import external Node.js modules. 4. Define functions - Write function declarations to create reusable blocks of code. 5. Execute the file - Run the file using node command followed by the file name. Any functions will be executed. 6. See output - Check the terminal for any output or errors from your running functions. So in summary, Node.js
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/ 25

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:

The area of the circle is: 78.5


The area of the circle with new radius is: 200.96

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;

// Display movie details using template literals


console.log(`Movie Name: ${movieName}`);
console.log(`Starring: ${starring.join(", ")}`);
console.log(`Language: ${language}`);
console.log(`Ratings: ${ratings}`);

OutPut:

Movie Name: The Godfather


Starring: Marlon Brando, Al Pacino, James Caan
Language: English
Ratings: 9.2

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;

// Calculate total price and discounted amount


const totalPrice = numTickets * ticketPrice;
const discountAmount = totalPrice * (discountPercent / 100);
const discountedPrice = totalPrice - discountAmount;

// 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;

// Check if booking is allowed and calculate total price


if (ticketPrice === null) {
console.log("Sorry, booking is not allowed for 6 or more seats.");
} else {
const totalPrice = numTickets * ticketPrice;
console.log(`Number of tickets: ${numTickets}`);
console.log(`Ticket price: Rs. ${ticketPrice}`);
console.log(`Total price: Rs. ${totalPrice}`);
}

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;

// Prompt user for number of tickets and validate input


do {
numTickets = Number(prompt(`Enter the number of tickets to book (maximum
${maxSeatsAllowed}):`));
} while (isNaN(numTickets) || numTickets <= 0 || numTickets > maxSeatsAllowed);

// Calculate total price based on number of tickets


let totalPrice = 0;
if (numTickets <= 2) {
totalPrice = numTickets * ticketPrice;
} else if (numTickets >= 6) {
console.log("Sorry, booking is not allowed for 6 or more seats.");
} else {
for (let i = 1; i <= numTickets; i++) {
totalPrice += i % 2 === 0 ? ticketPrice / 2 : ticketPrice;
}
}

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

4a)Module Name: In build Events and Handlers


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:

if (numSeats <= 2)

return numSeats * 150;

else if (numSeats >= 6)

return "Booking not allowed. Maximum of 5 seats allowed per transaction.";

Else

return numSeats * 200;


}

let numSeatsToBook = 4;

let totalPrice = calculateTotalPrice(numSeatsToBook);

Print the total price to the console

console.log("Total price for " + numSeatsToBook + " seats: Rs. " + totalPrice);

Output: Total price for 4 seats: Rs. 800

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;

Person(int age, String name)


{
this.name = name;
this.age = age;
}
}

class Employee extends Person


{
int emp_id;
int emp_salary;
Employee(int id, String name, int age, int salary)
{
super(age, name);
emp_id = id;
emp_salary = salary;
}

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);
}
}

public class Main


{
public static void main(String[] args)
{
Employee emp = new Employee(101, "Savas Akhtan", 32, 22340);
emp.printEmployeeDetails();
}
}

Output:

Employee ID : 101
Employee Name : Savas Akhtan
Employee Age : 32
Employee Salary : 22340

4c) Module Name: Javascript


Module Name: Working with Objects, Types of Objects, Creating Objects,
Combining and cloning Objects using Spread operator, Destructuring ObjectsBrowser
Object Model, Document Object Model

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:

Movie Name:”The Shawshank Redemotion”;


Starring:[“Tim Robbins”,”Morgan Freeman”],
Language:”English”,
Rating:3.5
Movie Name:”The God Father”,
Starring:[“Marlon Brando”,”Aipacino”],
Language:”Telugu”’
Rating:4
Movie Name: “The Dark Knight”,
Starring:[“Christian Bale”,”Heath Ledger”],
Language:”English”’
Rating:4

5b) Module Name: Creating Modules, Consuming Modules

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

6a) Module Name:How to use Node.js

Verify how to execute different functions successfully in the Node.js platform.

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");

fs.writeFile("output.txt", "Hello, world!", function (err)


{
if (err)
{
console.error(err);
} else
{
console.log("File written successfully");
}
});

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.

5. Use command-line arguments: Node.js provides access to the command-line


arguments passed to your script through the process.argv array. For example, if
you wanted to modify your hello.js script to output a custom message based on a
command-line argument, you could modify it like this:
javascript
const args = process.argv.slice(2);

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');

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


{
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!');
});

const port = 3000;

server.listen(port, ()
{
console.log(`Server running at http://localhost:${port}/`);
});
Output: Server running at http://localhost:3000/

6b) Module Name:Modular programming in Node.js


Write a Node.js module to show the workflow of Modularization of Node application

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;

console.log(`Addition: ${calculator.add(a, b)}`);


console.log(`Subtraction: ${calculator.subtract(a, b)}`);
console.log(`Multiplication: ${calculator.multiply(a, b)}`);
console.log(`Division: ${calculator.divide(a, b)}`);
Output: Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2

Express.js

Exercise-7

7a)Module Name: How Middleware works, Chaining of Middlewares, Types of Middlewares

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:

1. Handling POST submissions: To handle POST submissions, you can use


middleware that intercepts incoming requests and checks if the HTTP method is
POST. If it is, the middleware can parse the incoming data and pass it along to the
next step in the application's logic. You can use existing middleware libraries like
Express.js or write your own custom middleware for this purpose.
2. Displaying customized error messages: To display customized error messages, you
can use middleware that intercepts errors thrown by the application and formats
them in a user-friendly way. The middleware can also add additional information to
the error message, such as the stack trace or error code. This can help users
diagnose and resolve issues more easily. You can use existing middleware libraries
like express-validator or write your own custom middleware for this purpose.
3. Performing logging: To perform logging, you can use middleware that intercepts
incoming requests and outgoing responses and logs information about them. This
can include details such asthe request method, URL, response status, and response
time. You can use existing middleware libraries like Morgan or write your own
custom middleware for this purpose.

Types of Middlewares: There are several types of middleware that can be used in web
applications.

Some of the most common types are:

1.Application-level middleware: This middleware is specific to the application and is


used to handle tasks such as routing, session management, and error handling.

2.Third-party middleware: This middleware is created by third-party developers and


can be used to add additional functionality to the application, such as authentication or
caching.

3.System-level middleware: This middleware is used to handle tasks such as


compression, encryption, or traffic shaping at the network level.

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

Write a program to wrap the Schema into a Model object.

Program:

const mongoose = require('mongoose');

// Define your schema

const userSchema = new mongoose.Schema({

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

const User = mongoose.model('User', userSchema);

// Use the model to interact with the database

User.create({

firstName: 'John',

lastName: 'Doe',

email: '[email protected]',

age: 30

})

.then((result) => {

console.log('Created user:', result);

})

.catch((error) => {

console.error('Error creating user:', error);

});

Output: Created user:

id: 61eb23c67d7ccfd8e3870812,

firstName: 'John',

lastName: 'Doe',

email: '[email protected]',

age: 30,
}

Express.js

Exercise-8

8a) Module Name: CRUD Operations


Write a program to perform various CRUD (Create-Read-Update-Delete) operationsusing

program:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true });

const Schema = mongoose.Schema;

// Define a schema for the data


const mySchema = new Schema({
name: String,
age: Number,
email: String
});

// Create a model for the data


const MyModel = mongoose.model('MyModel', mySchema);

// 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);
}

async function readData()


{
const data = await MyModel.find({});
console.log('Data retrieved:', data);
}

async function updateData(id, update)


{
const data = await MyModel.findByIdAndUpdate(id, update, { new: true });
console.log('Data updated:', data);
}

async function deleteData(id)


{
const data = await MyModel.findByIdAndDelete(id);
console.log('Data deleted:', data);
}

// Call the CRUD operations


(async ()
{
console.log('Creating data...');
await createData();

console.log('\nRetrieving data...');
await readData();

console.log('\nUpdating data...');
await updateData('606d7eb765808c2a90ebcf6c', { name: 'Jane Doe' });

console.log('\nRetrieving data after update...');


await readData();

console.log('\nDeleting data...');
await deleteData('606d7eb765808c2a90ebcf6c');

console.log('\nRetrieving data after delete...');


await readData();
mongoose.connection.close();
})
Output: Creating data...
Data created: { _id: 606d7eb765808c2a90ebcf6c, name: 'John Doe', age: 30, email:
'[email protected]', __v: 0 }

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 }

Retrieving data after update...


Data retrieved: [ { _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:

const express = require('express');


const session = require('express-session');

const app = express();


app.use(session({
secret: 'mysecret',
resave: false,
saveUninitialized: false,
}));
app.post('/login', (req, res)
{
const username = req.body.username;
const password = req.body.password;
if (username === 'user' && password === 'password')
{
req.session.userId = 1;
res.send('You are now logged in.');
} else
{
res.status(401).send('Invalid username or password.');
}
});
app.get('/protected', (req, res)
{
if (!req.session.userId)
{
res.status(401).send('You must be logged in to access this resource.');
} else
{
res.send('You are authorized to access this resource.');
}
});
app.listen(3000, ()
{
console.log('Server listening on port 3000.');
});
Output:
POST /login
Content-Type: application/json

{
"username": "user",
"password": "password"
}
You are now logged in.

8c) Module Name: Why and What Security, Helmet Middleware


Implement security features in myNotes application.

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:

 npm install helmet

2. Require the Helmet package in your main application file:

javascript
 const helmet = require('helmet');

3.Use the helmet() middleware in your application:

app.use(helmet());

This will set various HTTP headers to improve the security of your application, including:

 X-XSS-Protection: Sets the X-XSS-Protection header to prevent cross-site


scripting (XSS) attacks.
 X-Content-Type-Options: Sets the X-Content-Type-Options header to
prevent MIME-type sniffing attacks.
 X-Frame-Options: Sets the X-Frame-Options header to prevent clickjacking
attacks.
 Referrer-Policy: Sets the Referrer-Policy header to control the amount of
information sent with the referrer header.

Typescript
Exercise-9

9a) Module Name: Basics of Type Script

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.

TypeScript is an open-source programming language developed and maintained by


Microsoft. It is a superset of JavaScript, which means any valid JavaScript code is also
valid TypeScript code. TypeScript adds optional static typing and other features to
JavaScript to help developers write more robust and scalable code.

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:

Here's an example code snippet in TypeScript:

let goldPlatinumPrice: number = 1000;

let pinkGoldPrice: number = 1100;

let silverTitaniumPrice: number = 1200;

console.log(`The price of the mobile in Gold Platinum color is $${goldPlatinumPrice}.`);

console.log(`The price of the mobile in Pink Gold color is $${pinkGoldPrice}.`);

console.log(`The price of the mobile in Silver Titanium color is $${silverTitaniumPrice}.`);

Output:

The price of the mobile in Gold Platinum color is $1000.

The price of the mobile in Pink Gold color is $1100.

The price of the mobile in Silver Titanium color is $1200.

9b) Module Name:FUNCTION


Define an arrow function inside the event handler to filter the product array with the
selected product object using the productId received by the function. Pass the selected
product object to the next screen.

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 = [

{ id: 1, name: 'Product 1', price: 100 },

{ id: 2, name: 'Product 2', price: 200 },

{ id: 3, name: 'Product 3', price: 300 },

];

function handleProductSelection(productId: number)

const selectedProduct = products.filter(product => product.id === productId)[0];

console.log(`Selected product:`, selectedProduct);

Output:

Product1: Mobile

Price:3000

Product 2: Watch

Price: 1000

Product 3:Ear Phones

Price: 1500

9c)Module Name: Parameter types and return types

Consider that developer needs to declare a function - getMobileByVendor which accepts


string as input parameter and returns the list of mobiles.
Program:

interface Mobile

name: string;

vendor: string;

function getMobileByVendor(vendor: string): Mobile[]

const mobiles: Mobile[] = [

{ name: "iPhone 12", vendor: "Apple" },

{ name: "Galaxy S21", vendor: "Samsung" },

{ name: "Pixel 5", vendor: "Google" },

{ name: "OnePlus 9", vendor: "OnePlus" }

];

return mobiles.filter((mobile) => mobile.vendor === vendor);

Output:

Mobiles by Apple: name: "iPhone 12", vendor: "Apple"

Mobiles by Samsung :name: "Galaxy S21", vendor: "Samsung

Mobiles by Google :name: "Pixel 5", vendor: "Google"

Mobiles by OnePlus: name: "OnePlus 9", vendor: "OnePlus"


Typescript

Exercise-10

10a)Module Name:Rest Parameter

Implement business logic for adding multiple Product values into a cart variable which is
type of string array.

Program:

// Initialize an empty cart array

let cart: string[] = [];

function addToCart(product: string):

void

cart.push(product);

addToCart("Product 1");

addToCart("Product 2");

addToCart("Product 3");

console.log("Cart contents:", cart);

Output:

Cart contents: [ Product 1: Laptop Product 2: Smart Watches Product 3: Mobiles]

10b)Module Name: Creating an interface

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;

let product: Product =

productId: 1234,

productName: 'Example Product'

};

console.log(`Product ID: ${product.productId}`);

console.log(`Product Name: ${product.productName}`);

Output: Product ID: 1234

Product Name: Mobile

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;
}

let myProduct: Product =

productId: 123,

productName: "Example Product"

};

console.log("Product ID: " + myProduct.productId);

console.log("Product Name: " + myProduct.productName);

Output: Product ID: 123

Product Name: Smart Watches

You might also like