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

Js Code

The document contains 8 JavaScript experiments involving different data types and operations: 1) Calculate areas of geometric shapes (triangle, rectangle, circle) by prompting user input 2) Generate multiplication table for a user-input number 3) Demonstrate string operations like length, case conversion, substring extraction etc. 4) Compare two strings using different comparison methods 5) Create a countdown timer that displays time remaining until a set date 6) Demonstrate array operations like display, remove element, check presence of element, empty array 7) Demonstrate inserting an object into an array and checking if a value is an array 8) Demonstrate set operations like union, intersection, difference, symmetric difference on sample sets

Uploaded by

Om Bhandare
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)
68 views

Js Code

The document contains 8 JavaScript experiments involving different data types and operations: 1) Calculate areas of geometric shapes (triangle, rectangle, circle) by prompting user input 2) Generate multiplication table for a user-input number 3) Demonstrate string operations like length, case conversion, substring extraction etc. 4) Compare two strings using different comparison methods 5) Create a countdown timer that displays time remaining until a set date 6) Demonstrate array operations like display, remove element, check presence of element, empty array 7) Demonstrate inserting an object into an array and checking if a value is an array 8) Demonstrate set operations like union, intersection, difference, symmetric difference on sample sets

Uploaded by

Om Bhandare
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

EXP 1 (Calculation of areas)

// Function to calculate the area of a triangle

function calculateTriangleArea(base, height) {

return 0.5 * base * height;

// Function to calculate the area of a rectangle

function calculateRectangleArea(length, width) {

return length * width;

// Function to calculate the area of a circle

function calculateCircleArea(radius) {

return Math.PI * radius * radius;

// Prompt the user to input values for triangle

var baseOfTriangle = parseFloat(prompt("Enter the base of the triangle:"));

var heightOfTriangle = parseFloat(prompt("Enter the height of the triangle:"));

// Prompt the user to input values for rectangle

var lengthOfRectangle = parseFloat(prompt("Enter the length of the rectangle:"));

var widthOfRectangle = parseFloat(prompt("Enter the width of the rectangle:"));

// Prompt the user to input value for circle

var radiusOfCircle = parseFloat(prompt("Enter the radius of the circle:"));

// Calculate areas

var areaOfTriangle = calculateTriangleArea(baseOfTriangle, heightOfTriangle);

var areaOfRectangle = calculateRectangleArea(lengthOfRectangle, widthOfRectangle);

var areaOfCircle = calculateCircleArea(radiusOfCircle);


// Display the results using alert()

alert("Area of the triangle: " + areaOfTriangle);

alert("Area of the rectangle: " + areaOfRectangle);

alert("Area of the circle: " + areaOfCircle);


EXP 2: (Multiplication table)
// Prompt the user to input a number for the multiplication table
const number = parseInt(prompt("Enter a number to generate its
multiplication table:"));

// Check if the input is a valid number


if (!isNaN(number)) {
// Generate and display the multiplication table
console.log(`Multiplication Table for ${number}:`);
for (let i = 1; i <= 10; i++) {
console.log(`${number} * ${i} = ${number * i}`);
}
} else {
console.log("Invalid input. Please enter a valid number.");
}
EXP 3: (String data type operations)
// Define a sample string

const sampleString = "Hello, this is a sample string for JavaScript operations.";

// Display the original string

console.log("Original String:", sampleString);

// Get the length of the string

const stringLength = sampleString.length;

console.log("Length of the String:", stringLength);

// Convert the string to uppercase and display

const upperCaseString = sampleString.toUpperCase();

console.log("Uppercase String:", upperCaseString);

// Convert the string to lowercase and display

const lowerCaseString = sampleString.toLowerCase();

console.log("Lowercase String:", lowerCaseString);

// Extract a substring and display

const substring = sampleString.substring(7, 18);

console.log("Substring (from index 7 to 18):", substring);

// Split the string into an array based on a delimiter and display

const splitString = sampleString.split(" ");

console.log("Split String Array:", splitString);

// Check if the string includes a specific word

const wordToCheck = "JavaScript";

const includesWord = sampleString.includes(wordToCheck);

console.log(`String includes the word "${wordToCheck}":`, includesWord);


// Replace a part of the string and display

const replacedString = sampleString.replace("JavaScript", "Node.js");

console.log("Replaced String:", replacedString);


EXP 4: (comparing two strings)
// Define two sample strings for comparison

const string1 = "Hello";

const string2 = "hello";

// Method 1: Using the '===' operator (strict equality)

console.log("Comparison using '===' (strict equality) operator:");

console.log(`'${string1}' === '${string2}':`, string1 === string2);

// Method 2: Using the '==' operator (loose equality)

console.log("\nComparison using '==' (loose equality) operator:");

console.log(`'${string1}' == '${string2}':`, string1 == string2);

// Method 3: Using the 'localeCompare()' method

console.log("\nComparison using 'localeCompare()' method:");

console.log(`Comparing '${string1}' with '${string2}':`, string1.localeCompare(string2));

// Method 4: Converting both strings to lowercase or uppercase for comparison

console.log("\nComparison after converting both strings to lowercase:");

const lowerString1 = string1.toLowerCase();

const lowerString2 = string2.toLowerCase();

console.log(`'${lowerString1}' === '${lowerString2}':`, lowerString1 === lowerString2);

// Method 5: Using 'toUpperCase()' and 'toLowerCase()' to compare case-insensitive

console.log("\nCase-insensitive comparison using 'toUpperCase()' and 'toLowerCase()':");

console.log(`Comparing '${string1}' with '${string2}' (case-insensitive):`, string1.toUpperCase() ===


string2.toUpperCase());
EXP 5: (Countdown timer)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Timer in JS</title>

</head>

<body>

<h2><b>Countdown Timer</b></h2>

<input type="datetime-local" name="" id="timer">

<button onclick="startTimer()">Start Timer</button>

<h3 id="result"></h3>

<script type="text/javascript">

function startTimer() {

let x = setInterval(function () {

let countDownDate = document.getElementById("timer").value;

let timer = new Date(countDownDate);

let now = new Date().getTime();

let distance = timer - now;

let days = Math.floor(distance / (1000 * 60 * 60 * 24));

let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

let seconds = Math.floor((distance % (1000 * 60)) / 1000);

document.getElementById("result").innerHTML = `Timer will end in ${days} d : ${hours} h :

${minutes} m : ${seconds} s`;

if (distance < 0) {

clearInterval(x); document.getElementById("result").innerHTML = "EXPIRED";

}, 1000);

</script>

</body>
</html>
EXP 6: (Array data operation)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Array Operations</title>

</head>

<body>

<h1>Array Operations</h1>

<br>

<label for="arr">Enter the array elements separated by spaces: </label>

<input type="text" name="arr" id="arr" />

<br>

<br>

<button type="button" onclick="arrayDisplay()">Display</button>

<h4 style="color: blue" id="arrDisp">Given array is : ?</h4>

<br>

<h2>Remove Specific Element from Array</h2>

<br>

<label for="remarr">Enter the array element to be removed: </label>

<input type="text" name="remarr" id="remarr" />

<br><br>

<button type="button" onclick="removeArrayElement()">Remove</button>

<h4 style="color: blue" id="arrRem">Array after removing element: ?</h4>

<br>

<h2>Check if Element Present in Array</h2>

<br>

<label for="chkarr">Enter the array element to be checked: </label>

<input type="text" name="chkarr" id="chkarr" />

<br><br>
<button type="button" onclick="checkArrayElement()">Check</button>

<h4 style="color: blue" id="arrChk">Array element present or absent? </h4>

<br>

<h2>Empty Array</h2>

<br>

<button type="button" onclick="emptyArray()">Empty</button>

<h4 style="color: blue" id="arrEmpty">Empty Array ?</h4>

<script>

function arrayDisplay() {

const inputArr = document.getElementById('arr').value.split(' ');

const displayElement = document.getElementById('arrDisp');

displayElement.textContent = 'Given array is: ' + inputArr.join(', ');

function removeArrayElement() {

const inputArr = document.getElementById('arr').value.split(' ');

const elementToRemove = document.getElementById('remarr').value;

const updatedArr = inputArr.filter(item => item !== elementToRemove);

const displayElement = document.getElementById('arrRem');

displayElement.textContent = 'Array after removing element: ' + updatedArr.join(', ');

function checkArrayElement() {

const inputArr = document.getElementById('arr').value.split(' ');

const elementToCheck = document.getElementById('chkarr').value;

const isPresent = inputArr.includes(elementToCheck);

const displayElement = document.getElementById('arrChk');

displayElement.textContent = 'Array element is ' + (isPresent ? 'present' : 'absent');

function emptyArray() {

const displayElement = document.getElementById('arrEmpty');

displayElement.textContent = 'Empty Array: ';


document.getElementById('arr').value = ''; // Clear the input field

</script>

</body>

</html>
Exp7: (Object and array)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Array and Object </title>

</head>

<body>

<h1>Array and Object </h1>

<script>

function insertObject(arr, obj) {

// Append the object to the array

arr.push(obj);

// document.write(arr);

function checkObject(arr) {

// Check if arr is an array

const result = Array.isArray(arr);

if (result) {

document.write(`[${arr}] is an array.`);

} else {

document.write(`[${arr}] is not an array.`);

// Original array

let array = [1, 2, 3];

// Object to add

let object = { x: 12, y: 8 };

// Check if the original array is an array

checkObject(array);
// Call the function to insert the object into the array

insertObject(array, object);

</script>

</body>

</html>
EXP 8: (Set Operations)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Set Operations</title>

</head>

<body>

<h1>Set Operations</h1>

<div id="output">

<!-- Output will be displayed here -->

</div>

<script>

// Define two sets

const setA = new Set([1, 2, 3, 4, 5]);

const setB = new Set([3, 4, 5, 6, 7]);

// Function to perform Union of two sets

function union(set1, set2) {

return new Set([...set1, ...set2]);

// Function to perform Intersection of two sets

function intersection(set1, set2) {

return new Set([...set1].filter(x => set2.has(x)));

// Function to perform Difference (set1 - set2)

function difference(set1, set2) {

return new Set([...set1].filter(x => !set2.has(x)));

// Function to perform Set Difference (symmetric difference)

function symmetricDifference(set1, set2) {

const diff1 = difference(set1, set2);

const diff2 = difference(set2, set1);


return new Set([...diff1, ...diff2]);

// Output element

const outputDiv = document.getElementById("output");

// Display the Set operations results

function displayResults() {

outputDiv.innerHTML += "<strong>Set A:</strong> " + [...setA].join(", ") + "<br>";

outputDiv.innerHTML += "<strong>Set B:</strong> " + [...setB].join(", ") + "<br><br>";

const unionSet = union(setA, setB);

outputDiv.innerHTML += "<strong>Union (A ∪ B):</strong> " + [...unionSet].join(", ") + "<br>";

const intersectionSet = intersection(setA, setB);

outputDiv.innerHTML += "<strong>Intersection (A ∩ B):</strong> " +

[...intersectionSet].join(", ") + "<br>";

const differenceAB = difference(setA, setB);

outputDiv.innerHTML += "<strong>Difference (A - B):</strong> " + [...differenceAB].join(", ") +

"<br>";

const symmetricDiff = symmetricDifference(setA, setB);

outputDiv.innerHTML += "<strong>Symmetric Difference (A △ B):</strong> " +

[...symmetricDiff].join(", ") + "<br>";

// Call the displayResults function to show the results on the screen

displayResults();

</script>

</body>

</html>
EXP9:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Website Home Page</title>

</head>

<body>

<h1>Welcome to Our Website</h1>

<br>

<button id="changeColorButton">Change Background Color (Mouseover)</button>

<br>

<br>

<a href="#" id="changeColorLink">Change Background Color (Focus)</a>

<script>

const button = document.getElementById("changeColorButton");

const link = document.getElementById("changeColorLink");

// Function to change the background color on mouseover

button.addEventListener("mouseover", function() {

document.body.style.backgroundColor = getRandomColor();

});

// Function to change the background color on focus for the anchor tag

link.addEventListener("focus", function() {

document.body.style.backgroundColor = getRandomColor();

});

// Helper function to generate a random color

function getRandomColor() {

const letters = "0123456789ABCDEF";

let color = "#";

for (let i = 0; i < 6; i++) {


color += letters[Math.floor(Math.random() * 16)];

return color;

</script>

</body>

</html>
EXP 9: (Handle different events)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Website Home Page</title>
</head>
<body>
<h1>Welcome to Our Website</h1>
<br>
<button id="changeColorButton">Change Background Color
(Mouseover)</button>
<br>
<br>
<a href="#" id="changeColorLink">Change Background Color
(Focus)</a>
<script>
const button = document.getElementById("changeColorButton");
const link = document.getElementById("changeColorLink");
// Function to change the background color on mouseover
button.addEventListener("mouseover", function() {
document.body.style.backgroundColor = getRandomColor();
});
// Function to change the background color on focus for the anchor
tag
link.addEventListener("focus", function() {
document.body.style.backgroundColor = getRandomColor();
});
// Helper function to generate a random color
function getRandomColor() {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>
EXP10: (form)
1.Index.html
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Student Information Form</title>

</head>

<body>

<h1>Student Information Form</h1>

<form id="studentForm" onsubmit="return validateForm()" action="submission_success.html"

method="post">

<label for="name">Name:</label>

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

<label for="address">Address:</label>

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

<label for="city">City:</label>

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

<label for="state">State:</label>

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

<label for="gender">Gender:</label>

<select id="gender" name="gender">

<option value="male">Male</option>

<option value="female">Female</option>

</select><br>

<label for="mobile">Mobile Number:</label>

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

<label for="email">Email ID:</label>

<input type="email" id="email" name="email" required><br>


<input type="submit" value="Submit">

</form>

<p id="errorMessages" style="color: red;"></p>

<script src="main.js"></script>

</body>

</html>

2. submission_success.html
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Submission Successful</title>

</head>

<body>

<h1>Congratulations and Welcome!</h1>

<p>Your information has been successfully submitted.</p>

</body>

</html>

3. main.js
function validateForm() {

const name = document.getElementById('name').value;

const mobile = document.getElementById('mobile').value;

const email = document.getElementById('email').value;

const errorMessages = document.getElementById('errorMessages');

errorMessages.innerHTML = ''; // Clear any previous error messages.

// Validation for correct name (only letters and spaces).

if (!/^[A-Za-z\s]+$/.test(name)) {
errorMessages.innerHTML += "Invalid name. Please enter a valid name.<br>";

return false;

// Validation for a valid mobile number.

if (!/^\d{10}$/.test(mobile)) {

errorMessages.innerHTML += "Invalid mobile number. Please enter a 10-digit number.<br>";

return false;

// Validation for a valid email address.

if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {

errorMessages.innerHTML += "Invalid email address. Please enter a valid email.<br>";

return false;

// If all validations pass, the form will be submitted.

return true;

}
EXP 10 : Display form on web
<!DOCTYPE html>

<html>

<head>

<title>Student Information Form</title>

</head>

<body>

<h1>Student Information Form</h1>

<form id="studentForm" onsubmit="return validateForm()">

<label for="fullName">Full Name:</label>

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

<label for="address">Address:</label>

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

<label for="city">City:</label>

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

<label for="state">State:</label>

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

<label for="gender">Gender:</label>

<input type="radio" id="male" name="gender" value="male" required>

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="female" required>

<label for="female">Female</label><br><br>

<label for="mobile">Mobile Number:</label>

<input type="text" id="mobile" name="mobile" pattern="[0-9]{10}" required><br><br>


<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<button type="submit">Submit</button>

</form>

<h2>Student Information</h2>

<p id="displayInfo"></p>

<script>

function validateForm() {

const fullName = document.getElementById('fullName').value;

const address = document.getElementById('address').value;

const city = document.getElementById('city').value;

const state = document.getElementById('state').value;

const gender = document.querySelector('input[name="gender"]:checked');

const mobile = document.getElementById('mobile').value;

const email = document.getElementById('email').value;

// Regex for valid name (allows alphabets, space, hyphen, and apostrophe)

const namePattern = /^[A-Za-z '-]+$/;

// Regex for valid mobile number (10 digits)

const mobilePattern = /^\d{10}$/;

if (!namePattern.test(fullName)) {

alert("Please enter a valid name.");

return false;

if (!mobilePattern.test(mobile)) {
alert("Please enter a valid 10-digit mobile number.");

return false;

// Display captured information upon successful validation

const displayInfo = document.getElementById('displayInfo');

displayInfo.innerHTML = `

<strong>Full Name:</strong> ${fullName}<br>

<strong>Address:</strong> ${address}<br>

<strong>City:</strong> ${city}<br>

<strong>State:</strong> ${state}<br>

<strong>Gender:</strong> ${gender.value}<br>

<strong>Mobile Number:</strong> ${mobile}<br>

<strong>Email:</strong> ${email}

`;

return false;

</script>

</body>

</html>

You might also like