Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Script Object Properties

The document contains multiple JavaScript programs demonstrating the use of various objects, methods, and control structures. It includes examples for document manipulation, array methods, math functions, string operations, date handling, conditional statements, loops, and functions for checking Armstrong numbers, factorials, Fibonacci series, prime numbers, and palindromes. Each program is structured in HTML with JavaScript embedded to showcase the functionality through user interaction.

Uploaded by

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

Java Script Object Properties

The document contains multiple JavaScript programs demonstrating the use of various objects, methods, and control structures. It includes examples for document manipulation, array methods, math functions, string operations, date handling, conditional statements, loops, and functions for checking Armstrong numbers, factorials, Fibonacci series, prime numbers, and palindromes. Each program is structured in HTML with JavaScript embedded to showcase the functionality through user interaction.

Uploaded by

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

JavaScript Pre-defined and User-defined Objects

Write a program using document object properties and methods.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Object Properties and Methods</title>
<script>
function demonstrateDocumentMethods() {
// Accessing the document title
document.title = "New Document Title"; // Changes the title of the page
alert("Page title changed to: " + document.title);

// Accessing and modifying the document body


document.body.style.backgroundColor = "#f0f8ff"; // Changes background color
alert("Background color changed!");

// Accessing an element by ID and modifying its content


document.getElementById("exampleText").innerHTML = "This text has been
changed using document.getElementById() method!";

// Accessing and modifying an element's style


document.getElementById("exampleText").style.color = "green";
document.getElementById("exampleText").style.fontSize = "20px";

// Changing the document's content using innerHTML


document.getElementById("contentDiv").innerHTML = "<p>New content has
been added to this div!</p>";

// Using createElement to dynamically add a new element


let newParagraph = document.createElement("p");
newParagraph.innerHTML = "This is a dynamically created paragraph!";
document.body.appendChild(newParagraph); // Adding the new element to the
body
}
</script>
</head>
<body>

<h1>Document Object Properties and Methods</h1>

<p id="exampleText">This is some example text.</p>


<div id="contentDiv">
<p>Original content of this div.</p>
</div>

<button onclick="demonstrateDocumentMethods()">Click to Demonstrate Document


Methods</button>

</body>
</html>

Write a program using array object properties and methods

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Object Properties and Methods</title>
<script>
function demonstrateArrayMethods() {
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];

alert("Original Array: " + fruits);

alert("Array Length: " + fruits.length);

fruits.push("Fig");
alert("Array after push: " + fruits);

fruits.pop();
alert("Array after pop: " + fruits);

fruits.shift();
alert("Array after shift: " + fruits);

fruits.unshift("Grapes");
alert("Array after unshift: " + fruits);

let sliceArray = fruits.slice(1, 3);


alert("Array after slice (from index 1 to 3): " + sliceArray);

let joinedString = fruits.join(", ");


alert("Array joined into a string: " + joinedString);

let index = fruits.indexOf("Date");


alert("Index of 'Date': " + index);

let reversedArray = fruits.reverse();


alert("Array after reverse: " + reversedArray);

let sortedArray = fruits.sort();


alert("Array after sort: " + sortedArray);

let splicedArray = fruits.splice(2, 1, "Honeydew");


alert("Array after splice (replacing 1 element at index 2 with 'Honeydew'): " +
fruits);
}
</script>
</head>
<body>

<h1>Array Object Properties and Methods</h1>

<button onclick="demonstrateArrayMethods()">Click to Demonstrate Array


Methods</button>

</body>
</html>

Write a program using math object properties and methods.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Object Properties and Methods</title>
<script>
function demonstrateMathMethods() {
let number = 16;
let negativeNumber = -5;
let piValue = Math.PI;
let randomValue = Math.random();
let powerBase = 2;
let powerExponent = 3;
let roundedNumber = 3.14159;

alert("Math.PI: " + piValue);

alert("Square root of " + number + ": " + Math.sqrt(number));

alert("Absolute value of " + negativeNumber + ": " + Math.abs(negativeNumber));

alert("Random number between 0 and 1: " + randomValue);

alert("2 raised to the power of 3: " + Math.pow(powerBase, powerExponent));

alert("Rounded value of " + roundedNumber + ": " +


Math.round(roundedNumber));

alert("Ceiling value of " + roundedNumber + ": " + Math.ceil(roundedNumber));

alert("Floor value of " + roundedNumber + ": " + Math.floor(roundedNumber));

alert("Maximum value from 2, 5, 10, 1: " + Math.max(2, 5, 10, 1));

alert("Minimum value from 2, 5, 10, 1: " + Math.min(2, 5, 10, 1));

alert("Sine of 90 degrees (Math.sin): " + Math.sin(Math.PI / 2));

alert("Cosine of 0 degrees (Math.cos): " + Math.cos(0));


}
</script>
</head>
<body>

<h1>Math Object Properties and Methods</h1>

<button onclick="demonstrateMathMethods()">Click to Demonstrate Math


Methods</button>

</body>
</html>
Write a program using string object properties and methods.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Object Properties and Methods</title>
<script>
function demonstrateStringMethods() {
let str = "Hello, World!";
let str2 = " JavaScript Programming ";
let str3 = "apple,banana,orange";

alert("Original string: " + str);

alert("String length: " + str.length);

alert("Character at index 4: " + str.charAt(4));

alert("Index of 'World': " + str.indexOf("World"));

alert("Substring from index 7 to 12: " + str.substring(7, 12));

alert("String in uppercase: " + str.toUpperCase());

alert("String in lowercase: " + str.toLowerCase());

alert("Trimmed string: '" + str2.trim() + "'");

alert("Split string by comma: " + str3.split(","));

alert("Replaced 'World' with 'JavaScript': " + str.replace("World", "JavaScript"));

alert("Concatenated strings: " + str.concat(" Welcome to ", "JavaScript!"));

alert("Checking if string starts with 'Hello': " + str.startsWith("Hello"));

alert("Checking if string ends with 'World!': " + str.endsWith("World!"));

alert("Extracting characters from index 7 to 11: " + str.slice(7, 12));


}
</script>
</head>
<body>

<h1>String Object Properties and Methods</h1>

<button onclick="demonstrateStringMethods()">Click to Demonstrate String


Methods</button>

</body>
</html>

Write a program using date object properties and methods.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Object Properties and Methods</title>
<script>
function demonstrateDateMethods() {
let currentDate = new Date();
let specificDate = new Date(2024, 11, 25); // December 25, 2024 (Months are 0-
indexed)

alert("Current Date and Time: " + currentDate);


alert("Current Year: " + currentDate.getFullYear());
alert("Current Month (0-11): " + currentDate.getMonth()); // 0-11 (0 = January, 11
= December)
alert("Current Day of the Month: " + currentDate.getDate());
alert("Current Day of the Week (0-6): " + currentDate.getDay()); // 0 = Sunday, 6 =
Saturday
alert("Current Hours: " + currentDate.getHours());
alert("Current Minutes: " + currentDate.getMinutes());
alert("Current Seconds: " + currentDate.getSeconds());
alert("Current Milliseconds: " + currentDate.getMilliseconds());

alert("Formatted Date: " + currentDate.toLocaleDateString());


alert("Formatted Time: " + currentDate.toLocaleTimeString());
alert("Formatted Date and Time: " + currentDate.toLocaleString());

alert("Specific Date (2024-12-25): " + specificDate);


alert("Specific Year: " + specificDate.getFullYear());
alert("Specific Month (0-11): " + specificDate.getMonth());
alert("Specific Day of the Month: " + specificDate.getDate());

specificDate.setFullYear(2025);
alert("Updated Year of Specific Date: " + specificDate.getFullYear());
}
</script>
</head>
<body>

<h1>Date Object Properties and Methods</h1>

<button onclick="demonstrateDateMethods()">Click to Demonstrate Date


Methods</button>

</body>
</html>

JavaScript Conditional Statements and Loops


Write a program which asks the user to enter three integers, obtains the numbers
from the user and outputs HTML text that displays the larger number followed by
the words “LARGER NUMBER” in an information message dialog. If the numbers
are equal, output HTML text as “EQUAL NUMBERS”.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Compare Numbers</title>
<script>
function compareNumbers() {
// Prompt the user to enter three integers
let num1 = parseInt(prompt("Enter the first integer:"));
let num2 = parseInt(prompt("Enter the second integer:"));
let num3 = parseInt(prompt("Enter the third integer:"));

// Check if the numbers are equal


if (num1 === num2 && num2 === num3) {
alert("EQUAL NUMBERS");
} else {
// Find the larger number
let largerNumber = Math.max(num1, num2, num3);
alert(largerNumber + " LARGER NUMBER");
}
}
</script>
</head>
<body>

<h1>Number Comparison</h1>

<button onclick="compareNumbers()">Click to Compare Numbers</button>

</body>
</html>

Write a program to display week days using switch case.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Week Days</title>
<script>
function displayWeekDay() {
// Prompt the user to enter a number (1-7)
let dayNumber = parseInt(prompt("Enter a number between 1 and 7 to display the
corresponding weekday:"));

// Use switch-case to display the weekday name


let dayName;
switch(dayNumber) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid input. Please enter a number between 1 and 7.";
break;
}
// Display the result
alert(dayName);
}
</script>
</head>
<body>

<h1>Display Week Days</h1>

<button onclick="displayWeekDay()">Click to Display Weekday</button>

</body>
</html>

Write a program to print 1 to 10 numbers using for, while and do-while loops.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loop Example</title>
<script>
function printNumbers() {
// Using for loop
let output = "Using for loop: <br>";
for (let i = 1; i <= 10; i++) {
output += i + " ";
}

// Using while loop


output += "<br>Using while loop: <br>";
let i = 1;
while (i <= 10) {
output += i + " ";
i++;
}

// Using do-while loop


output += "<br>Using do-while loop: <br>";
i = 1;
do {
output += i + " ";
i++;
} while (i <= 10);

// Display the result


document.getElementById("result").innerHTML = output;
}
</script>
</head>
<body>

<h1>Print Numbers from 1 to 10 using Different Loops</h1>

<button onclick="printNumbers()">Click to Print Numbers</button>


<div id="result"></div>

</body>
</html>

Develop a program to determine whether a given number is an ‘ARMSTRONG


NUMBER’ or not. [Eg: 153 is an Armstrong number, since sum of the cube of the
digits is equal to the number i.e.,13 + 53+ 33 = 153]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Armstrong Number Check</title>
<script>
function checkArmstrong() {
// Prompt the user to enter a number
let num = parseInt(prompt("Enter a number to check if it's an Armstrong
number:"));
let originalNum = num;
let sum = 0;
let numberOfDigits = num.toString().length;

// Calculate the sum of the cubes of each digit


while (num > 0) {
let digit = num % 10;
sum += Math.pow(digit, numberOfDigits);
num = Math.floor(num / 10);
}

// Check if the sum is equal to the original number


if (sum === originalNum) {
alert(originalNum + " is an Armstrong number.");
} else {
alert(originalNum + " is not an Armstrong number.");
}
}
</script>
</head>
<body>

<h1>Check Armstrong Number</h1>

<button onclick="checkArmstrong()">Click to Check</button>

</body>
</html>

JavaScript Functions and Events


Design a appropriate function should be called to display
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
<script>
function factorial(num) {
let fact = 1;
for (let i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}

function fibonacci(num) {
let fibSeries = [0, 1];
for (let i = 2; i <= num; i++) {
fibSeries.push(fibSeries[i - 1] + fibSeries[i - 2]);
}
return fibSeries;
}

function primeNumbers(num) {
let primes = [];
for (let i = 2; i <= num; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
return primes;
}

function isPalindrome(num) {
let originalNum = num;
let reversedNum = 0;
while (num > 0) {
let digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num = Math.floor(num / 10);
}
return originalNum === reversedNum;
}

function displayResults() {
let num = parseInt(prompt("Enter a number:"));

// Factorial
let fact = factorial(num);
alert("Factorial of " + num + " is: " + fact);

// Fibonacci series
let fibSeries = fibonacci(num);
alert("Fibonacci series up to " + num + ": " + fibSeries.join(", "));

// Prime numbers
let primes = primeNumbers(num);
alert("Prime numbers up to " + num + ": " + primes.join(", "));

// Palindrome check
let palindromeCheck = isPalindrome(num);
alert(num + " is " + (palindromeCheck ? "a Palindrome." : "not a Palindrome."));
}
</script>
</head>
<body>

<h1>Number Operations</h1>

<button onclick="displayResults()">Click to Enter a Number</button>

</body>
</html>

Design a HTML having a text box and four buttons named Factorial, Fibonacci,
Prime, and Palindrome. When a button is pressed an appropriate function should be
called to display
i. Factorial of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
<script>
function factorial(num) {
let fact = 1;
for (let i = 1; i <= num; i++) {
fact *= i;
}
alert("Factorial of " + num + " is: " + fact);
}

function fibonacci(num) {
let fibSeries = [0, 1];
for (let i = 2; i <= num; i++) {
fibSeries.push(fibSeries[i - 1] + fibSeries[i - 2]);
}
alert("Fibonacci series up to " + num + ": " + fibSeries.join(", "));
}

function primeNumbers(num) {
let primes = [];
for (let i = 2; i <= num; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
alert("Prime numbers up to " + num + ": " + primes.join(", "));
}

function isPalindrome(num) {
let originalNum = num;
let reversedNum = 0;
while (num > 0) {
let digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num = Math.floor(num / 10);
}
alert(originalNum + " is " + (originalNum === reversedNum ? "a Palindrome." : "not
a Palindrome."));
}

function getNumberAndProcess(action) {
let num = parseInt(document.getElementById("numberInput").value);
if (isNaN(num)) {
alert("Please enter a valid number.");
return;
}
if (action === "factorial") {
factorial(num);
} else if (action === "fibonacci") {
fibonacci(num);
} else if (action === "prime") {
primeNumbers(num);
} else if (action === "palindrome") {
isPalindrome(num);
}
}
</script>
</head>
<body>

<h1>Number Operations</h1>

<label for="numberInput">Enter a number:</label>


<input type="text" id="numberInput" />
<br /><br />

<button onclick="getNumberAndProcess('factorial')">Factorial</button>
<button onclick="getNumberAndProcess('fibonacci')">Fibonacci</button>
<button onclick="getNumberAndProcess('prime')">Prime</button>
<button onclick="getNumberAndProcess('palindrome')">Palindrome</button>

</body>
</html>

You might also like