0% found this document useful (0 votes)
9 views

Full Stack Development-Module-1

The document provides an overview of the MERN Stack, which consists of MongoDB, Express, React, and Node.js, aimed at simplifying full-stack web application development. It covers the installation and usage of Node.js, including its asynchronous model and package management with npm, as well as fundamental JavaScript concepts such as variables, data types, arrays, and functions. Additionally, it includes practical examples and coding exercises to illustrate the application of these technologies.

Uploaded by

nayakjahnvi44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Full Stack Development-Module-1

The document provides an overview of the MERN Stack, which consists of MongoDB, Express, React, and Node.js, aimed at simplifying full-stack web application development. It covers the installation and usage of Node.js, including its asynchronous model and package management with npm, as well as fundamental JavaScript concepts such as variables, data types, arrays, and functions. Additionally, it includes practical examples and coding exercises to illustrate the application of these technologies.

Uploaded by

nayakjahnvi44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

Full Stack Development

MERN Stack

By Dr. G.P.Hegde
What is MERN Stack?
MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications.
MERN Stack comprises of 4 technologies namely: MongoDB, Express, React and Node.js. It is designed to
make the development process smoother and easier.
•MongoDB: Non Relational Database

•Express: Node.js web server

•React: JavaScript Frontend Framework

•Node: JavaScript Web Server


MongoDB is the database used in the MERN stack. It is a NoSQL document-
Express is a web server framework meant for Node.js, oriented database, with a flexible schema and a JSON-based query language.
ReactJS and NodeJS are both JavaScript technologies. But the uses of
NodeJS and ReactJS are entirely different. NodeJS is a framework of
JavaScript which is mainly used for working with the backend
application or building the backend using JavaScript, whereas
ReactJS is a JavaScript front-end library.
Introduction to Node.js
• Node.js is JavaScript outside of a browser. The creators of Node.js just took Chrome’s V8 JavaScript
engine and made it run independently as a JavaScript runtime.
• Node.js Modules
• Modules are like libraries. You can include the functionality of another JavaScript file
• npm is the default package manager for Node.js. You can use npm to install third-party libraries
(packages) and also manage dependencies between them.
• Node.js has an asynchronous, event-driven, non-blocking input/output (I/O) model, as opposed to
using threads to achieve multitasking.
Steps for installation of Node-js
1. From Google, find node-js (v22.13.0) and download and install node-js
2. Give command in command prompt: node - - version
V22.13.0 is displayed and in command prompt give npm - -version it shows 10.9.2 then we can ensure that
node-js is installed successfully

3. If any error comes Update node js environmental variables


4. In vs code create new folder Npm-Node package manager
5. Install all necessary extensions :
a)Babbel javascript
b) Snippet shortcuts
c) Code runner
d) Live server
Installation of NodeJS
Node js environmental variables
Installation of extensions
In downloads
Doble-click and
install
Fiish

Click install-press yes-Finish


In windows –search- type cmd

Open command prompt and type node -- version

This indicates NodeJS is succefully installed with virtual


environment
Open Visual studio -> File -> OpenFolder->E:\-> NewFolder->JS->SelectFolder
Installation of extensions

Click on extension
Install Babel JAVAscript
Click on extension Click on extension
Install Snippet Shortcuts Install Code Runner

Click on extension
Install Live server
Babel is a free and open-source JavaScript transcompiler that is mainly used to convert ECMAScript
2015+ (ES6+) code into backwards-compatible JavaScript code that can be run by older JavaScript
engines. It allows web developers to take advantage of the newest features of the language

A snippet shortcut is a keyboard combination that activates a snippet to perform a specific action. Snippets can
be used for a variety of purposes, including adding code to programs, inserting text into emails, and running
JavaScript on web pages.
In visual studio->view ->explore->Jsfolder_>Click newfile_give name as helloworld.html
<!DOCTYPE html> Select languagemode-HTML
<html lang="en">
<head> Clickon Golive to run HTML files
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, World!</title>
</head>
<body>
<div id="message"></div>

<script>
// JavaScript to display "Hello, World!" in the div
document.getElementById('message').textContent = 'Hello, World!';
</script>
</body>
</html>

helloworld.html

<!DOCTYPE html>
<html lang="en">
<<body>
<div id="message"></div>
<script>
document.getElementById('message').textContent = 'Hello, World!';
</script>
</body>
</html
Module-1
Module-1 (FSD)
• Basic JavaScript Instructions
• Statements
• Comments
• Variables
• Data Types
• Arrays
• Strings
• Functions
• Methods & Objects
• Decisions & Loops
Statements
A script is a series of instructions that a computer can follow one by one. Each
individual instruction or step is known as statement. Statement should end with
semicolon. Java script is case sensitive. Examples are
Comments
Comments can be used to explain what your code does. It helps
to make your code easier to read and understand This can help
you and others who read your code
Multiline comments Single line comments

Control+? Short cut key for comment a line in visual studio code
Variables
A script will have to temporarily store the bits of information it needs to
do its job . It can store this data in variables.
A variable is a good name for this concept because the data stored in a
variable can change each time a script runs

Difference between var and let


JavaScript Variables let creates block-scope variables
but var creates function scope variables
• Automatically

• Using var
• Using let
• Using const
Example using let
let x = 5;
let y = 6;
let z = x + y;

Example using const


const x = 5;
const y = 6;
const z = x + y;

Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 +
price2;
One Statement, Many Variables
You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

Example
let person = "John Doe", carName = "Volvo", price = 200;

A declaration can span multiple lines:

Example
let person = "John Doe",
carName = "Volvo",
price = 200;
Redeclaring variables

let x=10;
{
let x=2;
}
console.log(x);

Output 10

var x=10;
{
var x=2;
}
console.log(x);

Output 2
Data types
JavaScript distinguishes between numbers, strings and true or
false values known as Booleans
JavaScript has 8 Datatypes
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
//js/book/index.html
<!DOCTYPE html> //js-folder-book->book.js
<html lang="en"> var username;
<head> var message;
<meta charset="UTF-8"> username = 'Molly';
<meta name="viewport" content="width=device-width, initial-scale=1.0"> message = 'See our upcoming range';
<meta http-equiv="X-UA-Compatible" content="ie=edge"> var elName = document.getElementById('name');
<title>HTML 5 Boilerplate</title> elName.textContent = username;
<link rel="stylesheet" href="style.css"> var elNote = document.getElementById('note');
</head> elNote.textContent = message;
<body>
<div>
<h1>Elderflower</h1>
<div id="content">hi
<div id="title">Howdy
<span id="name">friend</span>
</div>
<div id="note">
Take a look around...
</div>
</div>
</div>
<script src="book.js"> </script>
</body>
</html>
Six rules to be followed while declaring variables
1.The name must begin with a letter, dollar sign($) or ununderscore(_). It must
not start with a number
2. The variable name can contain letters, numbers, dollars sign or an underscore
that you must not use a dash or a period (.) in a variable name.
3. You cannot use keywords or reserve words. Keywords are special words that
tell the interpreter to do something .For example var is a keyword used to
declare a variable. Reserved words are ones that may be used in a future version
of JavaScript.
var a=8
var b=9
var c=a+b
Console.log(c)
4. All variable are case sensitive.
5. Use a name that describes the kind of information that the
variable stores. It means use proper name for declaring variable
names, (firstName, lastName, dot use fN , lN)
6. If your variable name is madeup of more than one word.
//jsfolder->book->ex3.html-
<!DOCTYPE html> //js->ex5.js
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
console.log(5 + 9);
window.alert(5 + 6);
</script>

</body>
</html>
//js->ex1.html
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Not single
quote

const a = 5;
const b = 10;
const sum = a + b;
console.log(`The sum is: ${sum}`);
// store input numbers
const num1 = 5;
const prompt = require('prompt-sync')();
const num2 = 3;
const num1 = parseInt(prompt('Enter the first number '));
// add two numbers
const num2 = parseInt(prompt('Enter the second number '));
const sum = num1 + num2;
//add two numbers
// display the sum
const sum = num1 + num2;
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
// display the sum
console.log(`The sum of ${num1} and ${num2} is ${sum}`);

In Vscode shell
npm install prompt-sync
ex1.html
<html lang="en">
<body>
<script src="ex1.js"></script> <!--
</body>
</html>

ex1.js
const num1 = parseInt(prompt('Enter the first number:'));
const num2 = parseInt(prompt('Enter the second number:'));
const sum = num1 + num2;
document.write(`The sum is: ${sum}`);
//js→ex2.html
<!DOCTYPE html>
<html>
<body>
<h2>My First JavaScript</h2>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
Arrays
An array is a special variable, which can hold more than one value:
const colors = ['white', 'black', 'custom']; Book\array2.html
Creating an Array <html lang="en">
<body>
<h2>First Color in the Array:</h2>
<p id="colors"></p>
<script src="array2.js"></script>
</body>
</html>

Book\array2.js
// Define an array of colors
const colors = ['white', 'black', 'custom'];
// Get the paragraph element by its ID
const el = document.getElementById('colors');
// Display the first element in the array
el.innerHTML = colors[0];
Array constructor
<!DOCTYPE html>
<html>
<body>
<p>Avoid use of [ ]. Use new Array() constructor concept</p>
<p id="demo"></p>
<script>
const points = new Array(40, 100, 1, 5, 25, 10);
//const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points[0];
</script>
</body>
</html>
Accessing and Changing Values in an Array
Book/array3.html
<html lang="en">
<body>
<h2>Update the third item in the
Array:</h2>
<p id="colors"></p>
<script src="array3.js"></script>
</body>
</html>

//create an array
var colors = new Array('white', 'black', 'custom');
//update the third item in the array
colors[2]='beige'
const e1 = document.getElementById('colors');
//replace with the third item from the array
e1.textContent = colors[2];
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>
Using the JavaScript Keyword new
<!DOCTYPE html> The following example also creates an
<html> Array, and assigns values to it:
<body>
<h1>JavaScript Arrays</h1> <!DOCTYPE html>
<html>
<p id="demo"></p> <body>
<h1>JavaScript Arrays</h1>
<script>
const cars = []; <p id="demo"></p>
cars[0]= "Saab";
cars[1]= "Volvo"; <script>
cars[2]= "BMW"; const cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML = cars; document.getElementById("demo").innerHTML = cars;
</script> </script>

</body> </body>
</html> </html>
Accessing Array Elements
You access an array element by referring to the index number:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>JavaScript array elements are accessed using numeric


indexes (starting from 0).</p>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>
Changing an Array Element
This statement changes the value of the first element in cars:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>JavaScript array elements are accessed using numeric


indexes (starting from 0).</p>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>
Converting an Array to a String
The JavaScript method toString() converts an array to a string of (comma separated) array values.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The toString() Method</h2>

<p>The toString() method returns an array as a comma separated string:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>

</body>
</html>
JavaScript uses names to access object properties

//js->book->arrays_demo.html
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>

<p>JavaScript uses names to access object properties.</p>


<p id="demo"></p>

<script>
const person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person.firstName;
</script>

</body>
</html>
Expressions
An expression evaluates in it a single value . There are two types
of expressions
Operators
Expressions rely on things called operators, they allow
programmers to create a single value from one or more values
Arithmetic operators
//js->book->arithmetic.html //js->book->arithmetic.js
<!DOCTYPE html> var subtotal = (13 + 1) * 5;
<html lang="en"> var shipping = 0.5 * (13 + 1);
<head> var total = subtotal + shipping;
<meta charset="UTF-8">
<meta name="viewport" content="width=device- var elSub =
width, initial-scale=1.0"> document.getElementById('subtotal');
<title>Order Total</title> elSub.textContent = subtotal;
</head>
<body> var elShip =
<p>Subtotal: <span id="subtotal"></span></p> document.getElementById('shipping');
<p>Shipping: <span id="shipping"></span></p> elShip.textContent = shipping;
<p>Total: <span id="total"></span></p>
var elTotal =
<script src="arithmetic.js"></script> document.getElementById('total');
</body> elTotal.textContent = total;
</html>
String operator
stringop.html
Using string operator <hl>Elderflower</hl>
<div id="content">
<div id="greeting"
class="message">Hello
<span id="name">friend</span>!
</div>
</div>
<script src="stringop.js"></script>

stringop.js
var greeting = 'Howdy';
var name = 'Molly';
var welcomeMessage = greeting + name + '!';
var el = document.getElementById('name');
el.textContent = welcomeMessage;
Summary of chapters studied
What is Function
Parameter passing in JavaScript user defined function
Js/practiceProgram.html
<html>
<body>
<p id="gph" ></p>
<script>
let z=sdm(2,3);
//document.getElementById("gph").innerHTML= ("the value of z is " +z);
window.alert(z);
// document.write(z)
// console.log(z)
function sdm(a,b){
let x=a+b;
return x;
}
</script>
</body>
</html>
Js/function-example.html
<html>
<body>
<p id="gph"></p>
<script src="function-example.js"></script>
</body>
</html>

Js/function-example.js

let z=calculate(2,3);
const y=document.getElementById("gph");
y.innerHTML=z;
function calculate(a,b)
{
let x=a+b
return x;
}
Program 1a Write a script that Logs "Hello, World!" to the console. Create a script that
calculates the sum of two numbers and displays the result in an alert box.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script>
function displayHelloWorld() {
alert("Hello World");
}

</script>
</head>
<body>
<button onclick="displayHelloWorld()">Click to Display Hello World</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script>
function displayHelloWorld() {
alert("Hello World");
}

function calculateSum() {
// Define two numbers
let number1 = 5; // You can change these values
let number2 = 10; // You can change these values
let sum = number1 + number2;

// Display the sum in an alert box


alert("The sum of " + number1 + " and " + number2 + " is: " + sum);
}
</script>
</head>
<body>
<button onclick="displayHelloWorld()">Click to Display Hello World</button>
<button onclick="calculateSum()">Click to Calculate Sum</button>
</body>
</html>
// Program No. 1b
// b. Create an array of 5 cities and perform the following operations: Log the total number of cities.
// Add a new city at the end. Remove the first city. Find and log the index of a specific city.
// Step 1: Create an array of 5 cities
let cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
// Step 2: Log the total number of cities
console.log("Total number of cities:", cities.length);
// Step 3: Add a new city at the end
cities.push("San Francisco");
// Step 4: Remove the first city
cities.shift();
// Step 5: Find and log the index of a specific city (e.g., "Chicago")
let cityIndex = cities.indexOf("Chicago");
console.log("Index of 'Chicago':", cityIndex);
clearInterval
// Program 2
// Read a string from the user, Find its length. Extract the word "JavaScript"
using substring() or slice(). Replace one word with another word and log the new
string. Write a function isPalindrome(str) that checks if a given string is a
palindrome (reads the same backward).

// Read a string from the user (for demonstration, we'll use a hardcoded string)
let str = "I am learning JavaScript programming.";

// Step 1: Find the length of the string


console.log("Length of the string:", str.length);

// Step 2: Extract the word "JavaScript" using substring() or slice()


let extractedWord = str.slice(14, 25); // Extracts "JavaScript"
console.log("Extracted word:", extractedWord);
// Step 3: Replace one word with another word and log the new string
let newStr = str.replace("JavaScript", "Python");
console.log("New string after replacement:", newStr);

// Step 4: Write a function to check if a string is a palindrome


function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
let cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

// Reverse the cleaned string


let reversedStr = cleanStr.split('').reverse().join('');
// Check if the original cleaned string equals the reversed string
return cleanStr === reversedStr;
}
// Test the isPalindrome function
let testStr = "A man a plan a canal Panama";
console.log(`Is the string "${testStr}" a palindrome?`, isPalindrome(testStr));
Declaring Function
Calling a Function
What is an Object ?
Objects are used to group together a set of variables and
functions to create a model of something you would
recognizing from the real world. In an object variables and
functions takes on new names object.variable
object.method
1.Creating an object using literal notation
2.Creating an object using constructor notation
function-example.js Create an object using Literal notation
var hotel = {
name: 'Quay' ,
rooms: 40,
booked: 25,
checkAvailability: function()
{
return this.rooms - this.booked;
}
};
var elName = document.getElementById('hotelName')
elName.textContent = hotel.name;
var elRooms =document.getElementById('rooms');
elRooms.textContent = hotel.checkAvailability();
<html>
<body>
<p id="hotelName"></p>
<p id="rooms"></p>
<script src="function-example.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<p id="demo"></p>
<script>
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display Data from the Object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
Create an object: Literal notation
Accessing a object and Dot notation
Creating a object constructor notation
Updating a Object
Creating many objects constructor notation
Creating a objects using constructor
Creating a object using constructor
var hotel = new Object();
hotel.name = 'Park'; Js-file
hotel.rooms=120;
hotel.booked=77;
hotel.checkAvailability = function()
{
return this.rooms - this.booked;
};
var elName = document.getElementById('hotelName');
elName.textContent = hotel.name;
var elRooms=document.getElementById('rooms');
elRooms.textContent = hotel.checkAvailability();

<html>
<body> Html-file
<p id="gph"></p>
<p id="hotelName"></p>
<p id="rooms"></p>
<script src="function-example.js"></script>
</body>
</html>
Create and Access objects constructor notation
Js-file
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = function() {
return this.rooms - this.booked;
};
}
// Creating instances
var quayHotel = new Hotel('Quay', 40, 25);
var parkHotel = new Hotel('Park', 120, 77);

// Updating the first hotel details


var details1 = quayHotel.name + ' rooms: ' + quayHotel.checkAvailability();
var elHotel1 = document.getElementById('hotel1');
if (elHotel1) {
elHotel1.textContent = details1; // Fix: Correct variable name
}

// Updating the second hotel details


var details2 = parkHotel.name + ' rooms: ' + parkHotel.checkAvailability();
var elHotel2 = document.getElementById('hotel2');
if (elHotel2) {
elHotel2.textContent = details2;
}
html-file
<html>
<body>
<!-- <p id="gph"></p>
<p id="hotelName"></p>
<p id="rooms"></p> -->
<p id="hotel1"></p>
<p id="hotel2"></p>
<script src="function-example.js"></script>
</body>
</html>
Adding and Removing Properties
Recap: Ways to Create objects
This keyword
Storing Data
If you want to access items via a property name or key, use an object (but note that
each key in the object must be unique ) If the order of the items is important then
use an array
The browser object model: The window object model
Using the browser object model
Decision making
There are often several places in a script where decision are made that
determine which lines of code should be run next. Flowcharts can help you
plan for these occasions
Using comparison operator
If-else1.js
var pass = 50;
var score=75;
var msg;
// Select message to write based on score
if (score >= pass) {
msg = 'Congratulations, you passed!'; }
else {
msg = 'Have another go!’;
}
var el = document.getElementById('answer');
el.textContent = msg;

If-else1.html
<html>
<body>
<p id="answer">Placeholder</p>
<script src="if-else1.js"></script>
</body>
</html>
Short Circuit Values
Loops For loop, While loop, Do While loop
book\for-ex1.html book\for-ex1.js

<html> for (var i=0; i<10; i++)


<body> document.write(i +' ')
<p id="answer"></p>
<script src="for-
ex1.js"></script>
</body>
</html>

for (let i = 0; i <= 9; i++)


{
document.write(i + "<br>");
}
Program3: Create an object student with properties: name (string), grade (number), subjects (array),
displayInfo() (method to log the student's details) Write a script to dynamically add a passed property to the
student object, with a value of true or false based on their grade. Create a loop to log all keys and values of
the student object.
js->Program3.js
// Create the student object
const student = {
name: "John Doe",
grade: 85,
subjects: ["Math", "Science", "English"],

// Method to display the student's information (no longer needed)


displayInfo: function() {
console.log(`Name: ${this.name}`);
console.log(`Grade: ${this.grade}`);
console.log(`Subjects: ${this.subjects.join(", ")}`);
}
};
// Add "passed" property dynamically
student.passed = student.grade >= 50;

// Display student info


//student.displayInfo();

// Log all properties


for (let key in student) {
console.log(`${key}:`, student[key]);
}
Here are three points to consider when you are working with loops.
<html>
<body>
<p id="answer"></p>
<script src="for-ex1.js"></script>
</body>
</html>

var scores=[24,32,17];
var arrayLength=scores.length;
var roundNumber=0;
var msg=' ';
var i;
for(i=0; i<arrayLength; i++)
{
roundNumber=(i+1);
msg+= 'Round'+ roundNumber+':';
msg+=scores[i]+'</br>'

}
document.getElementById('answer').innerHTML=msg;
var i=1;
var msg=' ';
while (i<10)
{
msg+=i+'x5='+i*5+'<br/>'
i++;
}
document.getElementById('ans').innerHTML=msg;

<html>
<body>
<p id="ans"></p>
<script src="while-ex1.js"></script>
<!-- <script src="for-ex2.js"></script> -->
</body>
</html>
Using Do While Loops
While-loop

while-example.html

<html>
<body>
<!-- <p id="gph"></p>
<p id=“blackboard"></p>
<script src=“while-example.js"></script>
</body>
</html>
while-example.js
var table = 3;
var operator = 'addition';
var i = 1;
var msg=' ';
if (operator == 'addition') {
while (i<11) {
msg+= i+ '+' +table + "=" + (i+table)+ '<br/>';
i++;
}
} else {
while (i<11) {
msg+=i+ 'x' + table + ' =' +(i*table)+'<br/>';
i++;
}
}
// Write the message into the page
var el= document.getElementById('blackboard');
el.innerHTML = msg;
//js->ex4.html
!DOCTYPE html>
<html lang="en">
<head> // js->ex4.js->Perform calculations
<meta charset="UTF-8"> let sum = num1 + num2;
<meta name="viewport" content="width=device-width, initial- let difference = num1 - num2;
scale=1.0"> let product = num1 * num2;
<title>Arithmetic Operations</title>
</head> // Display the results
<body> alert("Results:\n" +
<h1>Arithmetic Operations</h1> "Sum: " + sum + "\n" +
<p>Enter two numbers to calculate their sum, difference, and "Difference: " + difference + "\n" +
multiplication.</p> "Multiplication: " + product);
<button onclick="calculate()">Calculate</button> console.log("Sum of the two numbers is:", sum);
console.log("Difference of the two numbers is:", difference);
<script> console.log("Multiplication of the two numbers is:", product);
function calculate() { }
// Prompt the user to input two numbers </script>
let num1 = parseFloat(prompt("Enter the first number:")); </body>
let num2 = parseFloat(prompt("Enter the second </html>
number:"));

// Check if inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers.");
return;
//js->ex4.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Two Numbers</title>
</head>
<body>
<h1>Add Two Numbers</h1>
<p>Enter two numbers below and click "Add" to calculate the sum.</p>

<!-- Input fields for the numbers -->


<label for="num1">First Number:</label>
<input type="number" id="num1" placeholder="Enter first number">
<br><br>
<label for="num2">Second Number:</label>
<input type="number" id="num2" placeholder="Enter second number">
<br><br>
//js->ex4.html
<!-- Button to trigger the addition -->
<button onclick="addNumbers()">Add</button>

<!-- Display the result -->


<p id="result"></p>

<script src="ex4.js"></script>
</body>
</html>
// Function to add two numbers //js->ex4.js
function addNumbers() {
// Get the input values
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);

// Validate the inputs


if (isNaN(num1) || isNaN(num2)) {
console.log("Invalid input! Please enter valid numbers.");
document.getElementById("result").innerText = "Please enter valid numbers.";
return;
}

// Calculate the sum


const sum = num1 + num2;

// Display the result in the paragraph


document.getElementById("result").innerText = `The sum is: ${sum}`;

// Log the result to the console


console.log(`The sum of ${num1} and ${num2} is: ${sum}`);
}
//js->program1a.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script>
function displayHelloWorld() {
alert("Hello World");
}
function calculateSum() {
// Define two numbers
let number1 = 5; // You can change these values
let number2 = 10; // You can change these values
let sum = number1 + number2;

// Display the sum in an alert box


alert("The sum of " + number1 + " and " + number2 + " is: " + sum);
}
</script>
</head>
<body>
<button onclick="displayHelloWorld()">Click to Display Hello World</button>
<button onclick="calculateSum()">Click to Calculate Sum</button>
</body>
</html>
//js->book\array1.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Color Display</title>
</head>
<body>
<p id="colors">Placeholder</p>

<script src="array1.js"></script>
<!-- //<script src="arithmetic.js"></script>
-->
</body>
</html
//js->book->array1.js
// var colors = ["white", "black", "custom"];
//const colors = ['white', 'black', 'custom'];
var colors = new Array('red', 'blue', 'green');
colors[2]='pink'
const e1 = document.getElementById('colors');

You might also like