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.
`${var}`) are used to display results neatly.<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>
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.
<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>
<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>
<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>
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").
<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>
<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>
<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>
| 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) |
<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>
<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>
<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>
<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>
| 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. |
<!-- 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>
| 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 |
<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>
Set is a JavaScript collection of unique values. It automatically discards duplicates.
The spread operator ... converts a Set to an Array for filtering.
for...of loop is used to iterate over sets.
<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>