404184 (C) · Elective III

JavaScript Lab Manual

RMD Sinhgad School of Engineering, Warje, Pune · Dept. of E&TC
// Index of Experiments
01Multiplication Table 02Area of Triangle, Rectangle & Circle 03String: Reverse, Replace & Palindrome 04String Comparison Methods 05Countdown Timer 06Array Operations 07Set Operations 08Mouse & Focus Events 09Simple Calculator
01
A Program to generate the multiplication table of a given number.
Aim: Write a JavaScript program to generate the multiplication table of a given number.

prompt() displays a dialog box that prompts the user for input. It returns the typed string or null if the user clicks Cancel.

parseInt(value, radix) parses a string and converts it to an integer. Returns NaN if the first character cannot be converted to a number.

  • A for loop is used to iterate from 1 to 10 (or a user-defined range).
  • Template literals (`${var}`) are used to display results neatly.
prompt(message, default)
parseInt(value, radix)
for (let i = 1; i <= 10; i++) { ... }
HTML + JavaScript — Multiplication Table
<html>
<head>
  <title>To generate the multiplication table of a given number.</title>
</head>
<body>
<script>
  var table = 10;
  for (var i = 1; i <= 10; i++) {
    document.write(table + "x" + i + "=" + i * table + "<br>");
  }
</script>
</body>
</html>
Console
10x1=10 10x2=20 10x3=30 ... up to 10x10=100
The program successfully generates a multiplication table using a for loop and the document.write() method to display results on the web page.
02
A Program to calculate area of triangle, area of rectangle and area of circle.
Aim: Write a JavaScript program to calculate area of triangle, area of rectangle and area of circle.

Triangle: Area = (base × height) / 2  |  Using Heron's formula: s = (a+b+c)/2, Area = √(s·(s-a)·(s-b)·(s-c))

Rectangle: Area = length × width

Circle: Area = π × r²  — uses Math.PI and Math.sqrt()

Math.sqrt(x) returns the square root of x. Math.PI is the constant ≈ 3.14159.

A) Area of Triangle
<html><head>
  <title>JavaScript Program To Calculate The Area of a Triangle</title>
</head><body>
<script>
  const baseValue  = prompt('Enter the base of a triangle: ');
  const heightValue = prompt('Enter the height of a triangle: ');
  const areaValue   = (baseValue * heightValue) / 2;
  console.log(`The area of the triangle is ${areaValue}`);
</script>
</body></html>
B) Area of Rectangle
<html><head>
  <title>JavaScript Program To Calculate The Area of a Rectangle</title>
</head><body>
<script type="text/javascript">
  var l, w, a;
  l = 8;
  w = 6;
  a = l * w;
  document.write("Area of rectangle = " + a + " units");
</script>
</body></html>
C) Area of Circle
<html><head>
  <title>JavaScript Program To Calculate The Area of a Circle</title>
</head><body>
  <h1>Area of a circle</h1>
  Enter the radius: <input type="text" id="txtRadius" />
  <input type="button" value="Calculate" onClick=CalculateArea() />
  <script>
    function CalculateArea() {
      var radius = document.getElementById('txtRadius').value;
      alert("The area of the circle is " + (radius * radius * Math.PI));
    }
  </script>
</body></html>
Outputs
Triangle (base=4, height=6): The area of the triangle is 12 Rectangle (l=8, w=6): Area of rectangle = 48 units Circle (r=5): The area of the circle is 78.53981...
The program demonstrates calculation of areas using basic arithmetic operators and JavaScript's built-in Math.PI and Math.sqrt() functions.
03
A Program to perform Reverse string, Replace characters, and Palindrome check on a given string.
Aim: Write a JavaScript program to perform operations: Reverse string · Replace characters · Check Palindrome.

split("") — Splits string into array of characters.

reverse() — Reverses an array in place.

join("") — Joins array elements into a string.

replace(regex/str, newStr) — Replaces first match (string) or all matches (with /g regex flag).

Palindrome — A string is a palindrome if it reads the same forwards and backwards (e.g., "madam", "dad").

A) Reverse String
<html><head>
  <title>program to reverse a string</title>
</head><body>
<script type="text/javascript">
  function reverseString(str) {
    const arrayStrings  = str.split("");       // Step 1: split
    const reverseArray  = arrayStrings.reverse(); // Step 2: reverse
    const joinArray     = reverseArray.join("");  // Step 3: join
    return joinArray;
  }
  const string = prompt('Enter a string: ');
  const result = reverseString(string);
  console.log(result);
</script>
</body></html>
B) Replace Characters
<html><head>
  <title>program to replace a string</title>
</head><body>
<script type="text/javascript">
  const string  = 'Mr Red has a red house and a red car';
  const regex   = /red/g;           // /g = global (replace all)
  const newText = string.replace(regex, 'blue');
  console.log(newText);
</script>
</body></html>
C) Palindrome Check
<html><body>
<script type="text/javascript">
  function checkPalindrome(string) {
    const arrayValues       = string.split('');
    const reverseArrayValues = arrayValues.reverse();
    const reverseString     = reverseArrayValues.join('');
    if (string == reverseString) {
      console.log('It is a palindrome');
    } else {
      console.log('It is not a palindrome');
    }
  }
  const string = prompt('Enter a string: ');
  checkPalindrome(string);
</script>
</body></html>
Outputs
Reverse ("hello"): olleh Replace: Mr Red has a blue house and a blue car Palindrome ("madam"): It is a palindrome Palindrome ("hello"): It is not a palindrome
The program demonstrates string manipulation in JavaScript using split(), reverse(), join(), and the replace() method with regular expressions.
04
A Program to compare two strings using various methods.
Aim: Write a JavaScript program to compare two strings using various methods.
Method How it Works Returns
== (Equality) Direct comparison, case-sensitive true / false
toUpperCase() Converts both strings to uppercase then compares with === true / false
RegEx (gi) Creates a regex pattern from one string and tests the other; gi = global + case-insensitive true / false
localeCompare() Compares strings lexicographically with locale rules 0 (equal), -1 (before), 1 (after)
a) Using Equality Operator (==)
<script type="text/javascript">
  var stringFirst  = "javascript world";
  var stringSecond = "javascript world";
  var res = '';
  if (stringFirst == stringSecond) {
    res = 'strings are equal';
  } else {
    res = 'strings are not equal';
  }
  document.write("Output :- " + res);
</script>
b) Using toUpperCase()
<script type="text/javascript">
  const string1 = 'Are you like JavaScript Program';
  const string2 = 'javascript program';
  const result = string1.toUpperCase() === string2.toUpperCase();
  if (result) {
    console.log('The strings are similar.');
  } else {
    console.log('The strings are not similar.');
  }
</script>
c) Using RegEx
<script type="text/javascript">
  const string1 = 'JavaScript Program';
  const string2 = 'javascript program';
  const pattern = new RegExp(string1, "gi");
  const result  = pattern.test(string2);
  if (result) {
    console.log('The strings are similar.');
  } else {
    console.log('The strings are not similar.');
  }
</script>
d) Using localeCompare()
<script type="text/javascript">
  const string1 = 'This is the JavaScript Program';
  const string2 = 'this is the javascript program';
  const result  = string1.localeCompare(string2, undefined, { sensitivity: 'base' });
  if (result == 0) {
    console.log('The strings are similar.');
  } else {
    console.log('The strings are not similar.');
  }
</script>
Outputs
a) == operator: Output :- strings are equal b) toUpperCase(): The strings are not similar. c) RegEx (gi): The strings are similar. d) localeCompare: The strings are similar.
Four methods for string comparison were demonstrated. The localeCompare() with sensitivity:'base' and RegEx /gi flag both support case-insensitive comparison.
05
A Program to create a countdown timer.
Aim: Write a JavaScript program that will create a countdown timer.
Method Description
setInterval(fn, ms) Calls a function repeatedly at every ms milliseconds. Returns an ID.
clearInterval(id) Stops the interval set by setInterval().
setTimeout(fn, ms) Calls a function once after ms milliseconds.
clearTimeout(id) Cancels the timeout set by setTimeout().
Math.floor(x) Rounds down to the largest integer ≤ x.
new Date().getTime() Returns milliseconds elapsed since Jan 1, 1970.
Countdown Timer
<!-- Display the countdown timer in an element -->
<p id="demo"></p>
<script>
  // Set the date we're counting down to
  var countDownDate = new Date("Sep 1, 2022 15:35:25").getTime();

  // Update the count down every 1 second
  var x = setInterval(function() {
    var now      = new Date().getTime();
    var distance = countDownDate - now;  // time left in ms

    // Convert ms → days, hours, minutes, seconds
    var days    = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Display result
    document.getElementById("demo").innerHTML =
      days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

    // If expired, stop and display message
    if (distance < 0) {
      clearInterval(x);
      document.getElementById("demo").innerHTML = "EXPIRED";
    }
  }, 1000);
</script>
Browser Output
0d 0h 0m 23s ← (updates every second) EXPIRED ← (when countdown reaches 0)
A countdown timer was built using setInterval() to update every second, Math.floor() for time conversions, and clearInterval() to stop execution when the timer reaches zero.
06
A Program to create an array and perform operations: remove element, check value, empty array.
Aim: Write a JavaScript program that will create an array and perform: remove specific element · check if value exists · empty an array.
Method Action Returns
pop() Removes last element Removed element
shift() Removes first element Removed element
splice(index, count) Removes count elements from index Array of removed items
filter(fn) Creates new array with elements passing test New array
includes(value) Checks if array contains value true / false
indexOf(value) Finds first index of value; -1 if absent Index number
Array Operations (HTML with Buttons)
<html><body>
<h3>Demonstrate array operations</h3>
<button onclick="removeElement()">Remove Element</button>
<button onclick="chkValue()">Check value</button>
<button onclick="emptyArray()">Empty Array</button>

<script>
  function removeElement() {
    var shoeBrand = ["Nike", "Adidas", "Sparks", "RedTape"];
    var poppedElement = shoeBrand.pop(); // removes last: "RedTape"
    console.log("Removed: " + poppedElement);
    console.log("Remaining: " + shoeBrand);
    shoeBrand.splice(1, 2); // remove 2 elements from index 1
    console.log("After splice(1,2): " + shoeBrand);
  }

  function chkValue() {
    var carBrand = ["Maruti", "BMW", "Kia", "Tata"];
    var str1 = prompt("Enter carBrand Value");
    const hasValue = carBrand.includes(str1);
    if (hasValue) {
      console.log('Array contains: ' + str1);
    } else {
      console.log('Array does not contain: ' + str1);
    }
  }

  function emptyArray() {
    var carBrand = ["Maruti", "BMW", "Kia", "Tata"];
    carBrand.splice(0, carBrand.length); // remove all elements
    console.log("Empty Array: " + carBrand);
  }
</script>
</body></html>
Console
Remove: Removed: RedTape | Remaining: Nike,Adidas,Sparks After splice(1,2): Nike Check ("BMW"): Array contains: BMW Empty: Empty Array:
Various array operations — removal via pop() and splice(), value checking via includes(), and emptying via splice(0, length) — were demonstrated using event-driven HTML buttons.
07
A Program to illustrate different Set operations: Union, Intersection, Difference, Subset.
Aim: Write a JavaScript program to illustrate different Set operations like Union · Intersection · Difference · Set Difference (Subset).

Set is a JavaScript collection of unique values. It automatically discards duplicates.

  • Union (A ∪ B) — All elements from both sets.
  • Intersection (A ∩ B) — Only elements present in both sets.
  • Difference (A \ B) — Elements in A that are NOT in B.
  • Subset — Returns true if all elements of B are in A.

The spread operator ... converts a Set to an Array for filtering. for...of loop is used to iterate over sets.

Set Operations with Buttons
<html><head>
  <h2>Demonstrate Set Operations</h2>
  <p>set A = ['apple', 'mango', 'orange']</p>
  <p>set B = ['grapes', 'apple', 'banana']</p>
  <p>set C = ['apple', 'orange']</p>
  <button onclick="union()">Union</button>
  <button onclick="intersection()">Intersection</button>
  <button onclick="difference()">Difference</button>
  <button onclick="subset()">Subset</button>
<script>
  const setA = new Set(['apple', 'mango', 'orange']);
  const setB = new Set(['grapes', 'apple', 'banana']);
  const setC = new Set(['apple', 'orange']);

  function union() {
    let unionSet = new Set(setA);
    for (let i of setB) { unionSet.add(i); }
    console.log(unionSet);
  }

  function intersection() {
    let intersectionSet = new Set();
    for (let i of setB) {
      if (setA.has(i)) { intersectionSet.add(i); }
    }
    console.log(intersectionSet);
  }

  function difference() {
    let differenceSet = new Set(setA);
    for (let i of setB) { differenceSet.delete(i); }
    console.log(differenceSet);
  }

  function subset() {
    for (let i of setC) {
      if (!setA.has(i)) { console.log(false); return; }
    }
    console.log(true);
  }
</script>
Console
Union: Set {"apple","mango","orange","grapes","banana"} Intersection: Set {"apple"} Difference: Set {"mango","orange"} Subset (C⊆A): true
JavaScript Set operations — Union, Intersection, Difference, and Subset — were implemented using for...of loops, the has() method, and Set's add()/delete() methods.
08
A Program to create a Home page and change background color using onmouseover and onfocus events.
Aim: Write a JavaScript program to create a Home page and change background color using: On mouse over event · On focus event.

onmouseover — fires when the mouse pointer moves over an element.

onmouseout — fires when the mouse pointer leaves an element.

onfocus — fires when an element gains focus (user clicks or tabs into it).

onblur — fires when an element loses focus.

Background color is changed via: element.style.backgroundColor = "color" or element.style.background = "color"

mouseover & focus Events
<!DOCTYPE html>
<html><body>
  <h2>Demonstrate mouseOver() and focusFunction()</h2>

  <h3 id="demo"
       onmouseover="mouseOver()"
       onmouseout="mouseOut()">Mouse over me</h3>

  <input type="text"
         placeholder="Enter Text"
         id="focus"
         onfocus="focusFunction()"
         onblur="blurFunction()">

  <script>
    function mouseOver() {
      document.getElementById("demo").style.color = "red";
    }
    function mouseOut() {
      document.getElementById("demo").style.color = "black";
    }
    function focusFunction() {
      document.getElementById("focus").style.background = "yellow";
    }
    function blurFunction() {
      document.getElementById("focus").style.background = "red";
    }
  </script>
</body></html>
Browser Behavior
Mouse over h3: text color changes → red Mouse out h3: text color reverts → black Click input: background changes → yellow (onfocus) Click outside: background changes → red (onblur)
Event handling using onmouseover, onmouseout, onfocus, and onblur was demonstrated to dynamically change element styles in response to user interactions.
09
Design and implement a simple calculator using JavaScript for addition, subtraction, multiplication, division, and square.
Aim: Design and implement a simple calculator with input validation and alerts for invalid values.

parseFloat(value) — Converts string to floating-point number (handles decimals unlike parseInt).

document.getElementById("id").value — Reads value from an HTML input field.

alert(msg) — Displays a popup message box.

Calculator design uses separate functions for each operation triggered by button onclick events.

A switch statement can also be used to select the operation based on operator input.

Simple Calculator — HTML + JavaScript
<!DOCTYPE html>
<html><body>
  <h3>Calculator</h3>
  <input id="text1" placeholder="Enter Num1">
  <br><br>
  <input id="text2" placeholder="Enter Num2">
  <br><br>
  <button onclick="sum()">Add</button>
  <button onclick="diff()">Sub</button>
  <button onclick="mul()">Mult</button>
  <button onclick="div()">Div</button>
  <br><br>
  <input id="text3" placeholder="result">

  <script>
    function sum() {
      var x = parseFloat(document.getElementById("text1").value);
      var y = parseFloat(document.getElementById("text2").value);
      var s1 = x + y;
      document.getElementById("text3").value = s1;
      alert(s1);
    }
    function diff() {
      var x = parseFloat(document.getElementById("text1").value);
      var y = parseFloat(document.getElementById("text2").value);
      var s2 = x - y;
      document.getElementById("text3").value = s2;
      alert(s2);
    }
    function mul() {
      var x = parseFloat(document.getElementById("text1").value);
      var y = parseFloat(document.getElementById("text2").value);
      var s3 = x * y;
      document.getElementById("text3").value = s3;
      alert(s3);
    }
    function div() {
      var x = parseFloat(document.getElementById("text1").value);
      var y = parseFloat(document.getElementById("text2").value);
      var s4 = x / y;
      document.getElementById("text3").value = s4;
      alert(s4);
    }
  </script>
Browser Behavior
Input: Num1 = 10, Num2 = 5 Add → Result field shows 15, Alert: 15 Sub → Result field shows 5, Alert: 5 Mult → Result field shows 50, Alert: 50 Div → Result field shows 2, Alert: 2
A functional HTML/JavaScript calculator was designed with four arithmetic operations. Input values are read using getElementById(), converted with parseFloat(), and results displayed via alert() and an output field.