1. Find the Largest of Three Given Integers
function findLargest(a, b, c) {
return Math.max(a, b, c);
}
console.log(findLargest(10, 20, 15)); // 20
2. Explain Data Types with Example Program
let stringType = "Hello";
let numberType = 42;
let booleanType = true;
let objectType = { name: "John" };
let undefinedType;
let nullType = null;
console.log(typeof stringType, typeof numberType, typeof booleanType, typeof objectType, typeof undefinedType, typeof nullType);
3. Add Two Numbers Using a JavaScript Function
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(5, 10)); // 15
4. Convert a Given Number into Hours and Minutes
function convertToHoursAndMinutes(totalMinutes) {
let hours = Math.floor(totalMinutes / 60);
let minutes = totalMinutes % 60;
return hours + " hours and " + minutes + " minutes";
}
console.log(convertToHoursAndMinutes(130)); // 2 hours and 10 minutes
5. Print Odd Numbers from 1 to 100
for (let i = 1; i <= 100; i++) {
if (i % 2 !== 0) console.log(i);
}
6. Resize an Image on Mouse Events
const img = document.querySelector("img");
img.addEventListener("mouseover", () => img.style.width = "300px");
img.addEventListener("mouseout", () => img.style.width = "150px");
7. Perform a Binary Search
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
target < arr[mid] ? right = mid - 1 : left = mid + 1;
}
return -1;
}
console.log(binarySearch([1, 2, 3, 4, 5], 3)); // 2
8. Find the Most Frequent Item in an Array
function findMostFrequent(arr) {
let freq = {};
let maxFreq = 0, mostFrequent;
arr.forEach(item => {
freq[item] = (freq[item] || 0) + 1;
if (freq[item] > maxFreq) {
maxFreq = freq[item];
mostFrequent = item;
}
});
return mostFrequent;
}
console.log(findMostFrequent([1, 2, 3, 2, 1, 2])); // 2
9. Check Palindrome Number
function isPalindrome(num) {
return num.toString() === num.toString().split('').reverse().join('');
}
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
10. Print the Numbers from 0 to 50
for (let i = 0; i <= 50; i++) {
console.log(i);
}
11. Multiply Two Numbers Using Function
function multiply(a, b) {
return a * b;
}
console.log(multiply(5, 4)); // 20
12. Find if 1st January Will Be a Sunday Between 2014 and 2050
function isFirstJanSunday(year) {
return new Date(year, 0, 1).getDay() === 0;
}
for (let year = 2014; year <= 2050; year++) {
if (isFirstJanSunday(year)) console.log(`${year} Jan 1st is Sunday`);
}
13. Reverse the Elements of a Given Array
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]
14. Check Prime Number
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}
console.log(isPrime(11)); // true
15. Display Fibonacci Series
function fibonacci(n) {
let a = 0, b = 1;
while (n--) {
console.log(a);
[a, b] = [b, a + b];
}
}
fibonacci(5); // 0, 1, 1, 2, 3
16. Implement String Operations
let str = "Hello, World!";
console.log(str.toUpperCase()); // "HELLO, WORLD!"
console.log(str.toLowerCase()); // "hello, world!"
console.log(str.length); // 13
17. Extract Values at Specified Indexes from a Specified Array
function extractValues(arr, indexes) {
return indexes.map(i => arr[i]);
}
console.log(extractValues([1, 2, 3, 4, 5], [0, 2, 4])); // [1, 3, 5]
18. Design a Form to Accept User ID and Password
<form>
<label for="userID">User ID:</label><br>
<input type="text" id="userID" name="userID"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
19. Get the Filename Extension
function getFileExtension(filename) {
return filename.split('.').pop();
}
console.log(getFileExtension("example.jpg")); // jpg
20. Test Whether the First Character of a String is Uppercase
function isFirstCharacterUppercase(str) {
return str.charAt(0) === str.charAt(0).toUpperCase();
}
console.log(isFirstCharacterUppercase("Hello")); // true
console.log(isFirstCharacterUppercase("hello")); // false
21. Determine Whether a Given Year is a Leap Year or Not
function isLeapYear(year) {
return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
}
console.log(isLeapYear(2020)); // true
22. Create User Registration Form
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Register">
</form>
23. Get the Current Date and Time
let currentDate = new Date();
console.log(currentDate.toLocaleString()); // Current date and time
24. Accept One Number and Multiply by 3
let number = prompt("Enter a number:");
alert(number * 3);
25. Multiply Two Numbers
function multiply(a, b) {
return a * b;
}
console.log(multiply(6, 7)); // 42
26. Accept Two Numbers and Perform Subtraction
let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");
alert(num1 - num2);
27. Create Popup Box Alert and Confirm Box
alert("This is an alert box!");
let confirmResult = confirm("Do you want to proceed?");
console.log(confirmResult);
28. Find the Greater of Two Numbers
function findGreater(a, b) {
return a > b ? a : b;
}
console.log(findGreater(10, 5)); // 10
29. Pass a Function as a Parameter
function greetUser(name, greetingFn) {
greetingFn(name);
}
function sayHello(name) {
console.log("Hello, " + name);
}
greetUser("Alice", sayHello); // Hello, Alice
30. Display Current Day, Date, Month, Year, and Time
let currentDate = new Date();
console.log(currentDate.toDateString()); // Current date
console.log(currentDate.toTimeString()); // Current time
31. Implement Comparisons and Control Flow
let a = 10, b = 20;
if (a > b) {
console.log(`${a} is greater than ${b}`);
} else {
console.log(`${b} is greater than ${a}`);
}
32. Accept a Number from User and Calculate the Sum of Its Digits
function sumOfDigits(num) {
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum;
}
console.log(sumOfDigits(1234)); // 10
33. Print Your Name
console.log("John Doe");
34. Generate a Random Hexadecimal Color Code
function generateHexColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
console.log(generateHexColor()); // Random Hex Color
35. Swap Two Numbers Without Using a Third Variable
let a = 5, b = 10;
[a, b] = [b, a];
console.log(`a: ${a}, b: ${b}`); // a: 10, b: 5
36. Rotate a String
function rotateString(str, n) {
return str.slice(n) + str.slice(0, n);
}
console.log(rotateString("hello", 2)); // llohe
37. Get the First n Fibonacci Numbers
function fibonacci(n) {
let a = 0, b = 1;
let fib = [];
while (n--) {
fib.push(a);
[a, b] = [b, a + b];
}
return fib;
}
console.log(fibonacci(5)); // [0, 1, 1, 2, 3]
38. Display the Current Day and Time in the Following Format
let now = new Date();
let day = now.toLocaleDateString();
let time = now.toLocaleTimeString();
console.log(`Today is ${day} and the time is ${time}`);
39. Change the Capitalization of All Letters in a Given String
function changeCase(str) {
return str.split('').map(char => {
return char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}).join('');
}
console.log(changeCase("Hello World")); // hELLO wORLD
40. Generate All Permutations of an Array's Elements
function permute(arr) {
let result = [];
if (arr.length === 0) return [];
if (arr.length === 1) return [arr];
for (let i = 0; i < arr.length; i++) {
let rest = arr.slice(0, i).concat(arr.slice(i + 1));
let perms = permute(rest);
for (let j = 0; j < perms.length; j++) {
result.push([arr[i]].concat(perms[j]));
}
}
return result;
}
console.log(permute([1, 2, 3]));
41. Sort the Elements of an Array in Ascending Order
let arr = [5, 2, 8, 1, 3];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3, 5, 8]
42. Demonstrate the Switch Statement
let day = 3;
switch (day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
case 3: console.log("Wednesday"); break;
default: console.log("Invalid day");
}
43. Perform Arithmetic Operations of Two Numbers
let a = 10, b = 5;
console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);
44. Display the Largest Integer Among Two Integers
let a = 8, b = 12;
console.log(Math.max(a, b)); // 12
45. Find the Factorial of a Number
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
46. Check Whether the Given Number is Palindrome or Not
function isPalindrome(num) {
let str = num.toString();
return str === str.split('').reverse().join('');
}
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
47. Print the Elements of an Array
let arr = [1, 2, 3, 4, 5];
arr.forEach(item => console.log(item));
48. Define a User Defined Function for Sorting the Values in an Array
function customSort(arr) {
return arr.sort((a, b) => a - b);
}
console.log(customSort([5, 3, 8, 1])); // [1, 3, 5, 8]
49. Sort the Items of an Array
let arr = [10, 2, 5, 7, 4];
arr.sort((a, b) => a - b);
console.log(arr); // [2, 4, 5, 7, 10]
50. Check Whether the Given String is Palindrome or Not
function isStringPalindrome(str) {
return str === str.split('').reverse().join('');
}
console.log(isStringPalindrome("racecar")); // true
console.log(isStringPalindrome("hello")); // false
51. Accept Number and Display the Square of It
let num = prompt("Enter a number:");
alert(`The square of the number is: ${Math.pow(num, 2)}`);
52. Verify a Given Number is Even or Odd
let num = 15;
if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
53. Validate Email ID Using Regular Expression
let email = "test@example.com";
let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
console.log(regex.test(email)); // true
54. Replace the Word 'System' with 'Web' in the Given Text
let text = "This is a system application.";
let newText = text.replace("system", "web");
console.log(newText); // "This is a web application."
55. Print Corresponding Day of the Week Using Switch Statement
let dayNumber = 3;
switch (dayNumber) {
case 1: console.log("Sunday"); break;
case 2: console.log("Monday"); break;
case 3: console.log("Tuesday"); break;
case 4: console.log("Wednesday"); break;
case 5: console.log("Thursday"); break;
case 6: console.log("Friday"); break;
case 7: console.log("Saturday"); break;
default: console.log("Invalid day");
}
56. Convert Temperatures Between Celsius and Fahrenheit
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
console.log(celsiusToFahrenheit(25)); // 77
console.log(fahrenheitToCelsius(77)); // 25
57. Demonstrate Event Handling
let button = document.querySelector("button");
button.addEventListener("click", () => alert("Button clicked"));
58. Check Whether a Person is Eligible to Vote
let age = 20;
if (age >= 18) {
console.log("Eligible to vote");
} else {
console.log("Not eligible to vote");
}
59. Implement XMLHttpRequest (XHR) Object
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com", true);
xhr.onload = () => console.log(xhr.responseText);
xhr.send();
60. Determine Whether a Given Year is a Leap Year
function isLeapYear(year) {
return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
}
console.log(isLeapYear(2020)); // true
61. Display All Prime Numbers Between 1 and 100
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
for (let i = 1; i <= 100; i++) {
if (isPrime(i)) console.log(i);
}
62. Calculate Days Left Until Next Christmas
function daysUntilChristmas() {
let today = new Date();
let christmas = new Date(today.getFullYear(), 11, 25); // December 25th
if (today > christmas) {
christmas.setFullYear(today.getFullYear() + 1);
}
let diff = christmas - today;
return Math.floor(diff / (1000 * 60 * 60 * 24));
}
console.log(daysUntilChristmas());
63. Get the Window Width and Height Any Time the Window is Resized
window.addEventListener('resize', () => {
console.log(`Window width: ${window.innerWidth}, height: ${window.innerHeight}`);
});
64. Find Whether a Number is Divisible by 2 and 3
let num = 12;
if (num % 2 === 0 && num % 3 === 0) {
console.log(`${num} is divisible by 2 and 3.`);
} else {
console.log(`${num} is not divisible by 2 and 3.`);
}
65. Prime Number Check
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
console.log(isPrime(7)); // true
console.log(isPrime(10)); // false
66. Swap Two Variables
let a = 5, b = 10;
[a, b] = [b, a];
console.log(`a: ${a}, b: ${b}`); // a: 10, b: 5
67. Accept Two Integers and Display the Result by Multiplying by 3
function multiplyBy3(num1, num2) {
return (num1 * 3) + (num2 * 3);
}
console.log(multiplyBy3(5, 10)); // 45
68. Find Out the Factorial of a Given Number
function factorial(num) {
if (num === 0) return 1;
return num * factorial(num - 1);
}
console.log(factorial(6)); // 720
69. Convert a String to Title Case
function toTitleCase(str) {
return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
}
console.log(toTitleCase("hello world!")); // "Hello World!"
70. Accept a Number and Display the Sum of Its Digits
function sumOfDigits(num) {
return num.toString().split('').reduce((sum, digit) => sum + +digit, 0);
}
console.log(sumOfDigits(12345)); // 15
71. Create a Simple Calculator
function calculator(num1, num2, operator) {
switch (operator) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
default: return "Invalid operator";
}
}
console.log(calculator(5, 3, '+')); // 8
console.log(calculator(5, 3, '/')); // 1.6667
72. Reverse the Order of Characters in the String
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // "olleh"
73. Display the Current Day and Time
let now = new Date();
let currentDayTime = now.toLocaleString();
console.log(`Current date and time: ${currentDayTime}`);
74. Check If a Number is Odd or Even
let num = 15;
console.log(num % 2 === 0 ? 'Even' : 'Odd');
75. Get the Length of a JavaScript Object
let obj = { name: "John", age: 30, city: "New York" };
console.log(Object.keys(obj).length); // 3
76. Sort a List of Elements Using Quick Sort
function quickSort(arr) {
if (arr.length <= 1) return arr;
let pivot = arr[arr.length - 1];
let left = [], right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) left.push(arr[i]);
else right.push(arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(quickSort([5, 3, 8, 1, 4])); // [1, 3, 4, 5, 8]
77. Accept a String and Display It in Lowercase and Uppercase
let str = "Hello World";
console.log(str.toLowerCase()); // "hello world"
console.log(str.toUpperCase()); // "HELLO WORLD"
78. Factorial
function factorial(num) {
if (num === 0) return 1;
return num * factorial(num - 1);
}
console.log(factorial(4)); // 24
79. Using Any Five Events
document.getElementById("btnClick").addEventListener("click", () => alert("Button Clicked"));
document.getElementById("btnHover").addEventListener("mouseover", () => console.log("Mouse Over"));
document.getElementById("btnDoubleClick").addEventListener("dblclick", () => console.log("Double Clicked"));
document.getElementById("btnFocus").addEventListener("focus", () => console.log("Input Focused"));
document.getElementById("btnBlur").addEventListener("blur", () => console.log("Input Lost Focus"));
80. Read XML File and Display Data in a Neat Format
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let xml = xhr.responseXML;
let data = xml.getElementsByTagName("item");
for (let i = 0; i < data.length; i++) {
console.log(data[i].textContent);
}
}
};
xhr.send();
81. Fibonacci Series
function fibonacci(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib;
}
console.log(fibonacci(7)); // [0, 1, 1, 2, 3, 5, 8]
82. Remove the Whitespaces from a Given String
let str = " Hello World! ";
let newStr = str.trim();
console.log(newStr); // "Hello World!"
83. Find the Most Frequent Item in an Array
function mostFrequent(arr) {
let freqMap = {};
let maxCount = 0;
let mostFrequentItem = null;
arr.forEach(item => {
freqMap[item] = (freqMap[item] || 0) + 1;
if (freqMap[item] > maxCount) {
maxCount = freqMap[item];
mostFrequentItem = item;
}
});
return mostFrequentItem;
}
console.log(mostFrequent([1, 2, 3, 1, 2, 1])); // 1
84. Show the Current Date and Time
let now = new Date();
console.log(now.toString());
85. Sum the Multiples of 3 and 5 Under 1000
let sum = 0;
for (let i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
}
console.log(sum); // 233168
86. Shuffle an Array
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements
}
return arr;
}
console.log(shuffleArray([1, 2, 3, 4, 5])); // Randomly shuffled array
### 87. **Count the Vowels in a String**
```javascript
function countVowels(str) {
let vowels = 'aeiou';
return str.split('').filter(char => vowels.includes(char.toLowerCase())).length;
}
console.log(countVowels("Hello World")); // 3
88. Find the Largest Number in an Array
let arr = [10, 5, 8, 22, 14];
console.log(Math.max(...arr)); // 22
89. Find the Index of an Element in an Array
let arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(30)); // 2
90. Remove All Duplicate Elements from an Array
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
91. Accept Two Numbers and Perform Addition
function addTwoNumbers(num1, num2) {
return num1 + num2;
}
console.log(addTwoNumbers(10, 20)); // 30
92. Validate User Login Page
function validateLogin(username, password) {
if (username === "user" && password === "password123") {
return "Login successful!";
} else {
return "Invalid username or password.";
}
}
console.log(validateLogin("user", "password123")); // Login successful!
console.log(validateLogin("user", "wrongpass")); // Invalid username or password.
93. Display Hello World on the Screen
document.body.innerHTML = "Hello, World!";
94. Develop a Calculator Application to Perform All the Arithmetic Operations
function calculator(num1, num2, operator) {
switch (operator) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
case '%': return num1 % num2;
default: return "Invalid operator";
}
}
console.log(calculator(5, 3, '+')); // 8
console.log(calculator(5, 3, '*')); // 15
95. Create a Simple Calculator in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
</head>
<body>
<input id="num1" type="number" placeholder="Enter first number">
<input id="num2" type="number" placeholder="Enter second number">
<select id="operation">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<button onclick="performCalculation()">Calculate</button>
<div id="result"></div>
<script>
function performCalculation() {
let num1 = parseFloat(document.getElementById('num1').value);
let num2 = parseFloat(document.getElementById('num2').value);
let operator = document.getElementById('operation').value;
let result;
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
document.getElementById('result').innerText = `Result: ${result}`;
}
</script>
</body>
</html>
96. Read User Registration Details
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<form id="registrationForm">
<label for="username">Username:</label>
<input type="text" id="username" required><br>
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<label for="password">Password:</label>
<input type="password" id="password" required><br>
<button type="submit">Submit</button>
</form>
<div id="registrationResult"></div>
<script>
document.getElementById('registrationForm').addEventListener('submit', function(event) {
event.preventDefault();
let username = document.getElementById('username').value;
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
document.getElementById('registrationResult').innerHTML =
`Registration Successful! Username: ${username}, Email: ${email}`;
});
</script>
</body>
</html>
97. Perform Arithmetic Operations
function arithmeticOperations(num1, num2) {
return {
sum: num1 + num2,
difference: num1 - num2,
product: num1 * num2,
quotient: num1 / num2
};
}
console.log(arithmeticOperations(10, 5));
// {sum: 15, difference: 5, product: 50, quotient: 2}
98. Use Select Element of Form Tag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select Example</title>
</head>
<body>
<form>
<label for="colors">Choose a color:</label>
<select id="colors">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<button type="button" onclick="displaySelectedColor()">Submit</button>
</form>
<p id="selectedColor"></p>
<script>
function displaySelectedColor() {
let selectedColor = document.getElementById('colors').value;
document.getElementById('selectedColor').innerText = `You selected: ${selectedColor}`;
}
</script>
</body>
</html>
99. Print Multiplication Table of a Given Number Using Loop
function multiplicationTable(num) {
for (let i = 1; i <= 10; i++) {
console.log(`${num} x ${i} = ${num * i}`);
}
}
multiplicationTable(5);
100. Reverse an Array
function reverseArray(arr) {
return arr.reverse();
}
console.log(reverseArray([1, 2, 3, 4, 5])); // [5, 4, 3, 2, 1]
101. Create an Object from the Given Key-Value Pairs
function createObject(keys, values) {
let obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
return obj;
}
let keys = ["name", "age", "city"];
let values = ["John", 30, "New York"];
console.log(createObject(keys, values));
// {name: "John", age: 30, city: "New York"}
102. Illustrate Callback Function
function greetUser(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greetUser("John", sayGoodbye);
103. Add Items to a Blank Array and Display Them
let arr = [];
arr.push(10);
arr.push(20);
arr.push(30);
console.log(arr); // [10, 20, 30]
104. Get the Current Date in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Date</title>
</head>
<body>
<p id="currentDate"></p>
<script>
document.getElementById("currentDate").innerText = new Date().toLocaleDateString();
</script>
</body>
</html>
105. Remove Items from a Dropdown List
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Items from Dropdown</title>
</head>
<body>
<select id="dropdown">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
<button onclick="removeOption()">Remove Option</button>
<script>
function removeOption() {
let dropdown = document.getElementById('dropdown');
dropdown.removeChild(dropdown.options[dropdown.selectedIndex]);
}
</script>
</body>
</html>
106. Link Banner Advertisement to Different URL
<a href="https://example.com">
<img src="banner.jpg" alt="Banner Ad" />
</a>
107. Target a Given Value in a Nested JSON Object Based on the Given Key
let obj = {
user: {
name: "John",
address: {
city: "New York",
zip: "10001"
}
}
};
function findValueByKey(obj, key) {
for (let k in obj) {
if (k === key) {
return obj[k];
}
if (typeof obj[k] === "object") {
return findValueByKey(obj[k], key);
}
}
}
console.log(findValueByKey(obj, "city")); // "New York"
108. Check If a Number is Positive, Negative, or Zero
function checkNumber(num) {
if (num > 0) {
return "Positive";
} else if (num < 0) {
return "Negative";
} else {
return "Zero";
}
}
console.log(checkNumber(5)); // Positive
console.log(checkNumber(-3)); // Negative
console.log(checkNumber(0)); // Zero
109. Find Area of Circle
function areaOfCircle(radius) {
return Math.PI * Math.pow(radius, 2);
}
console.log(areaOfCircle(5)); // 78.53981633974483
110. Print Numbers from 1 to 10 Using For Loop
for (let i = 1; i <= 10; i++) {
console.log(i);
}
111. Validate the Fields of Login Page
function validateLoginForm(username, password) {
if (username === "" || password === "") {
return "Please fill in both fields.";
}
if (username.length < 3) {
return "Username must be at least 3 characters long.";
}
if (password.length < 6) {
return "Password must be at least 6 characters long.";
}
return "Login successful!";
}
console.log(validateLoginForm("john", "pass123")); // Login successful!
console.log(validateLoginForm("", "pass123")); // Please fill in both fields.
112. Check Armstrong Number
function isArmstrongNumber(num) {
let strNum = num.toString();
let sum = 0;
let length = strNum.length;
for (let i = 0; i < length; i++) {
sum += Math.pow(Number(strNum[i]), length);
}
return sum === num;
}
console.log(isArmstrongNumber(153)); // true
console.log(isArmstrongNumber(123)); // false
113. Form Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" required><br>
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
let username = document.getElementById('username').value;
let email = document.getElementById('email').value;
if (username === "" || email === "") {
alert("Please fill in all fields.");
} else {
alert("Form submitted successfully!");
}
});
</script>
</body>
</html>
114. Remove Specified Elements from the Left of a Given Array of Elements
function removeLeftElements(arr, n) {
return arr.slice(n);
}
console.log(removeLeftElements([1, 2, 3, 4, 5], 2)); // [3, 4, 5]
115. Declare and Initialize a Variable
let myVar = 10;
console.log(myVar); // 10
116. Recursion Example
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
117. Remove Duplicates from an Array
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 3, 2, 4, 5, 3])); // [1, 2, 3, 4, 5]
118. Calculate Area of Triangle
function areaOfTriangle(base, height) {
return 0.5 * base * height;
}
console.log(areaOfTriangle(5, 10)); // 25
119. Merge Two Arrays While Removing All Duplicates
function mergeArrays(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
console.log(mergeArrays([1, 2, 3], [3, 4, 5])); // [1, 2, 3, 4, 5]
120. Count the Number of Unique Alphabets Present in a Given String
function countUniqueAlphabets(str) {
let uniqueAlphabets = new Set(str.replace(/[^a-zA-Z]/g, '').toLowerCase());
return uniqueAlphabets.size;
}
console.log(countUniqueAlphabets("Hello World!")); // 7
121. Solve Quadratic Equation
function solveQuadratic(a, b, c) {
let discriminant = Math.pow(b, 2) - (4 * a * c);
if (discriminant > 0) {
let root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
let root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
return `Roots are ${root1} and ${root2}`;
} else if (discriminant === 0) {
let root = -b / (2 * a);
return `Root is ${root}`;
} else {
return "No real roots";
}
}
console.log(solveQuadratic(1, -3, 2)); // Roots are 2 and 1
122. Demonstrate Arrays
let arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));
123. Demonstrate Math Objects
let num = 16;
console.log(Math.sqrt(num)); // 4
console.log(Math.pow(2, 3)); // 8
console.log(Math.random()); // Random number
124. Accept a Number from the User and Find Its Factorial
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Calculator</title>
</head>
<body>
<label for="num">Enter a number:</label>
<input type="number" id="num">
<button onclick="calculateFactorial()">Calculate Factorial</button>
<p id="result"></p>
<script>
function calculateFactorial() {
let num = document.getElementById('num').value;
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
document.getElementById('result').innerText = `Factorial: ${result}`;
}
</script>
</body>
</html>
125. Password Validation Based on the Following Conditions
function validatePassword(password) {
if (password.length < 8) {
return "Password must be at least 8 characters long.";
}
if (!/[A-Z]/.test(password)) {
return "Password must contain at least one uppercase letter.";
}
if (!/[0-9]/.test(password)) {
return "Password must contain at least one number.";
}
return "Password is valid.";
}
console.log(validatePassword("Pass1234")); // Password is valid.
console.log(validatePassword("pass1234")); // Password must contain at least one uppercase letter.
126. Get the Last Element from a Given Array
function getLastElement(arr) {
return arr[arr.length - 1];
}
console.log(getLastElement([1, 2, 3, 4])); // 4
127. Add Two Numbers
function add(num1, num2) {
return num1 + num2;
}
console.log(add(10, 20)); // 30
128. Round Off the Integer Using Math Function
let number = 5.67;
console.log(Math.round(number)); // 6
129. Find the Largest Element in a Nested Array
let arr = [1, [2, 3], [4, 5], 6];
let largest = Math.max(...arr.flat());
console.log(largest); // 6
130. Remove Items from a Drop-Down List
<select id="dropdown">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
<button onclick="removeOption()">Remove Banana</button>
<script>
function removeOption() {
let dropdown = document.getElementById('dropdown');
for (let i = 0; i < dropdown.options.length; i++) {
if (dropdown.options[i].value === 'banana') {
dropdown.remove(i);
break;
}
}
}
</script>
131. Check Whether 1st January Will Be a Sunday Between 2014 and 2050
function checkSunday() {
for (let year = 2014; year <= 2050; year++) {
let date = new Date(year, 0, 1);
if (date.getDay() === 0) { // 0 is Sunday
console.log(`${year} - January 1st is a Sunday`);
}
}
}
checkSunday();
132. Check Whether a Given Number is Perfect or Not
function isPerfectNumber(num) {
let sum = 0;
for (let i = 1; i < num; i++) {
if (num % i === 0) {
sum += i;
}
}
return sum === num;
}
console.log(isPerfectNumber(6)); // true (6 is a perfect number)
133. Check Whether Entered Number is Prime or Not
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
console.log(isPrime(5)); // true
console.log(isPrime(10)); // false
134. Get the Window Width and Height Any Time the Window is Resized
window.addEventListener('resize', function() {
console.log(`Width: ${window.innerWidth}, Height: ${window.innerHeight}`);
});
135. Get Integers in the Range (x, y) Using Recursion
function getRange(x, y) {
if (x <= y) {
console.log(x);
getRange(x + 1, y);
}
}
getRange(1, 5); // 1 2 3 4 5
136. Design a Simple Calculator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
</head>
<body>
<input type="number" id="num1" placeholder="Enter number 1">
<input type="number" id="num2" placeholder="Enter number 2">
<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<button onclick="multiply()">Multiply</button>
<button onclick="divide()">Divide</button>
<p id="result"></p>
<script>
function add() {
let num1 = parseFloat(document.getElementById('num1').value);
let num2 = parseFloat(document.getElementById('num2').value);
document.getElementById('result').innerText = `Result: ${num1 + num2}`;
}
function subtract() {
let num1 = parseFloat(document.getElementById('num1').value);
let num2 = parseFloat(document.getElementById('num2').value);
document.getElementById('result').innerText = `Result: ${num1 - num2}`;
}
function multiply() {
let num1 = parseFloat(document.getElementById('num1').value);
let num2 = parseFloat(document.getElementById('num2').value);
document.getElementById('result').innerText = `Result: ${num1 * num2}`;
}
function divide() {
let num1 = parseFloat(document.getElementById('num1').value);
let num2 = parseFloat(document.getElementById('num2').value);
document.getElementById('result').innerText = `Result: ${num1 / num2}`;
}
</script>
</body>
</html>
137. Demo Alert Box, Conditional Box, and Prompt Box
<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Show Confirm</button>
<button onclick="showPrompt()">Show Prompt</button>
<script>
function showAlert() {
alert("This is an alert box!");
}
function showConfirm() {
let result = confirm("Do you want to proceed?");
alert(result ? "You clicked OK!" : "You clicked Cancel!");
}
function showPrompt() {
let userInput = prompt("Please enter your name:");
alert(`Hello, ${userInput}!`);
}
</script>
138. Construct a Pattern Using a Nested For Loop
function printPattern(n) {
let result = '';
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
result += '*';
}
result += '\n';
}
console.log(result);
}
printPattern(5);
0 Comments