JavaScript Programs for Beginners

1. Convert a Given Number to Hours and Minutes

function convertToHoursAndMinutes(num) {
    let hours = Math.floor(num / 60);
    let minutes = num % 60;
    console.log(`${hours} hours and ${minutes} minutes`);
}
convertToHoursAndMinutes(125);  // 2 hours and 5 minutes

2. Factorial of a Number Using Recursion

function factorial(num) {
    if (num === 0 || num === 1) {
        return 1;
    }
    return num * factorial(num - 1);
}
console.log(factorial(5));  // 120

3. Calculate the Area of a Triangle

function areaOfTriangle(base, height) {
    return (base * height) / 2;
}
console.log(areaOfTriangle(10, 5));  // 25

4. Square of a Number

function square(num) {
    return num * num;
}
console.log(square(4));  // 16

5. Print Multiplication Table of the Entered Number

function multiplicationTable(num) {
    for (let i = 1; i <= 10; i++) {
        console.log(`${num} x ${i} = ${num * i}`);
    }
}
multiplicationTable(5);

6. Validate User Login Page Using jQuery

$(document).ready(function() {
    $("#loginForm").submit(function(event) {
        let username = $("#username").val();
        let password = $("#password").val();
        if (username === "" || password === "") {
            alert("Both fields are required!");
            event.preventDefault();
        }
    });
});

7. Test if Character at Given Index is Lowercase

function isLowerCase(str, index) {
    return str[index] === str[index].toLowerCase();
}
console.log(isLowerCase("Hello", 1));  // true

8. Print Prime Numbers

function printPrimes() {
    for (let i = 2; i <= 100; i++) {
        let isPrime = true;
        for (let j = 2; j <= Math.sqrt(i); j++) {
            if (i % j === 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            console.log(i);
        }
    }
}
printPrimes();

9. Different Ways of Taking Input

// 1. Prompt method
let name = prompt("Enter your name:");

// 2. HTML form input
let inputField = document.getElementById("inputField").value;

// 3. Using command line (in Node.js)
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.question("What is your favorite color? ", function(color) {
    console.log(`Your favorite color is ${color}`);
    rl.close();
});

10. Validate Password

function validatePassword(password) {
    const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    return regex.test(password);
}
console.log(validatePassword("Password123"));  // true

11. Simple Calculator

function simpleCalculator(a, b, operator) {
    switch (operator) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
        default: return "Invalid operator";
    }
}
console.log(simpleCalculator(5, 3, "+"));  // 8

12. Print Odd Numbers Using While Loop

let num = 1;
while (num <= 20) {
    if (num % 2 !== 0) {
        console.log(num);
    }
    num++;
}

13. Search a Date (MM/DD/YYYY) Within a String

function searchDate(str) {
    const regex = /\b\d{2}\/\d{2}\/\d{4}\b/;
    return str.match(regex);
}
console.log(searchDate("Today's date is 04/09/2025"));  // ['04/09/2025']

14. Find Prime Number

function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}
console.log(isPrime(7));  // true

15. Wish a User at Different Hours of the Day

function wishUser() {
    let hours = new Date().getHours();
    if (hours < 12) {
        console.log("Good Morning!");
    } else if (hours < 18) {
        console.log("Good Afternoon!");
    } else {
        console.log("Good Evening!");
    }
}
wishUser();

16. Check if a Given Positive Number is a Multiple of 3 or 7

function isMultipleOf3or7(num) {
    return num % 3 === 0 || num % 7 === 0;
}
console.log(isMultipleOf3or7(21));  // true

17. Store Names of Employees and Display Them

let employees = ["John", "Jane", "Mike", "Anna"];
employees.forEach(employee => {
    console.log(employee);
});

18. Create Rollover Effect for Three Images

document.getElementById("image1").onmouseover = function() {
    this.src = "newImage1.jpg";
};
document.getElementById("image1").onmouseout = function() {
    this.src = "originalImage1.jpg";
};
// Repeat for other images

19. Get the Current Date on Button Click

function getCurrentDate() {
    let date = new Date();
    alert(date.toDateString());
}

20. Implement Abstraction Concept

class Animal {
    makeSound() {
        throw "This method must be implemented by subclasses";
    }
}

class Dog extends Animal {
    makeSound() {
        console.log("Woof!");
    }
}
let dog = new Dog();
dog.makeSound();  // Woof!

Sure! I'll provide the JavaScript programs for the next 50 tasks you requested. Here's the continuation with the next 50 JavaScript programs:


21. Find Leap Years in a Given Range of Years

function findLeapYears(start, end) {
    for (let year = start; year <= end; year++) {
        if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
            console.log(year);
        }
    }
}
findLeapYears(2000, 2025);

22. Get Sum of All Array Elements Using For Loop and ForEach Loop

let arr = [1, 2, 3, 4, 5];

// Using For Loop
let sum1 = 0;
for (let i = 0; i < arr.length; i++) {
    sum1 += arr[i];
}
console.log(sum1);  // 15

// Using ForEach Loop
let sum2 = 0;
arr.forEach(num => sum2 += num);
console.log(sum2);  // 15

23. Implement a Slideshow for Website Advertisement

let images = ["img1.jpg", "img2.jpg", "img3.jpg"];
let currentIndex = 0;

function changeImage() {
    document.getElementById("adImage").src = images[currentIndex];
    currentIndex = (currentIndex + 1) % images.length;
}
setInterval(changeImage, 3000);  // Change image every 3 seconds

24. Check if the Entered Number is Odd or Even

function checkOddEven(num) {
    if (num % 2 === 0) {
        console.log("Even");
    } else {
        console.log("Odd");
    }
}
checkOddEven(7);  // Odd

25. Calculate Area of Rectangle

function areaOfRectangle(length, width) {
    return length * width;
}
console.log(areaOfRectangle(5, 10));  // 50

26. Get the Website URL Loading Page

console.log(window.location.href);

27. Accept Integer and Display the Result by Multiplying It with 3

function multiplyByThree(num) {
    console.log(num * 3);
}
multiplyByThree(4);  // 12

28. Compute the Sum of an Array of Integers

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);  // 15

29. Sort the Array Elements

let arr = [5, 3, 8, 1, 2];
arr.sort((a, b) => a - b);
console.log(arr);  // [1, 2, 3, 5, 8]

30. Add an Element to Array

let arr = [1, 2, 3];
arr.push(4);
console.log(arr);  // [1, 2, 3, 4]

31. Test if the First Character of a String is Uppercase or Not

function isFirstCharUpperCase(str) {
    return str[0] === str[0].toUpperCase();
}
console.log(isFirstCharUpperCase("Hello"));  // true

32. Count the Number of Words in a String

function countWords(str) {
    return str.split(' ').length;
}
console.log(countWords("Hello World!"));  // 2

33. Get the Current Date in Hindi

let date = new Date();
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString('hi-IN', options));

34. Implement Polymorphism

class Animal {
    speak() {
        console.log("Animal speaks");
    }
}

class Dog extends Animal {
    speak() {
        console.log("Dog barks");
    }
}

let dog = new Dog();
dog.speak();  // Dog barks

35. Check Odd or Even Number

function checkOddEven(num) {
    return num % 2 === 0 ? "Even" : "Odd";
}
console.log(checkOddEven(9));  // Odd

36. Set Paragraph Background Color

document.getElementById("para").style.backgroundColor = "yellow";

37. Swap Two Numbers

let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b);  // 10, 5

38. Reverse a Given String

function reverseString(str) {
    return str.split('').reverse().join('');
}
console.log(reverseString("hello"));  // "olleh"

39. Display Information Box as Soon as Page Loads

window.onload = function() {
    alert("Welcome to the page!");
};

40. Find Largest Among 5 Numbers

function findLargest(numbers) {
    return Math.max(...numbers);
}
console.log(findLargest([10, 20, 30, 40, 50]));  // 50

41. Generate a Random Number

console.log(Math.floor(Math.random() * 100));  // Random number between 0 and 99

42. Link Banner Advertisement to Different URLs

document.getElementById("banner").onclick = function() {
    window.location.href = "https://www.example.com";
};

43. Input Name and Address of a Visitor and Display a Greeting Message

let name = prompt("Enter your name:");
let address = prompt("Enter your address:");
alert(`Hello ${name}, welcome from ${address}!`);

44. Check if the Given Year is a Leap Year

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
console.log(isLeapYear(2024));  // true

45. Print Factorial of a Given Number

function factorial(num) {
    if (num === 0 || num === 1) {
        return 1;
    }
    return num * factorial(num - 1);
}
console.log(factorial(5));  // 120

46. Form Validation

function validateForm() {
    let name = document.getElementById("name").value;
    if (name === "") {
        alert("Name is required!");
        return false;
    }
    return true;
}

47. Display Student Information

let student = {
    name: "John",
    age: 20,
    grade: "A"
};
console.log(student);

48. Calculate Area of Circle

function areaOfCircle(radius) {
    return Math.PI * radius * radius;
}
console.log(areaOfCircle(5));  // 78.53981633974483

49. Demo Local and Global Variables

let globalVar = "I'm global";

function demoLocalVar() {
    let localVar = "I'm local";
    console.log(localVar);  // Local variable
    console.log(globalVar);  // Global variable
}

demoLocalVar();

50. Get the Extension of a Filename

function getExtension(filename) {
    return filename.split('.').pop();
}
console.log(getExtension("image.jpg"));  // "jpg"

Sure! Here's the next set of 50 JavaScript programs based on your requirements:


51. Convert Kilometers to Centimeters

function convertKilometersToCentimeters(km) {
    return km * 100000;
}
console.log(convertKilometersToCentimeters(5));  // 500000 cm

52. Generate First 10 Fibonacci Numbers

function generateFibonacci() {
    let a = 0, b = 1, c;
    console.log(a);
    console.log(b);
    for (let i = 3; i <= 10; i++) {
        c = a + b;
        console.log(c);
        a = b;
        b = c;
    }
}
generateFibonacci();

53. Check if a Given Number is Even or Odd

function checkEvenOdd(num) {
    return num % 2 === 0 ? "Even" : "Odd";
}
console.log(checkEvenOdd(8));  // Even

54. Using JavaScript Built-In Objects

let date = new Date();
console.log(date.toDateString());  // Current date

55. Display First 10 Even Numbers Using For Loop

for (let i = 2; i <= 20; i += 2) {
    console.log(i);
}

56. Validate Email Based on Conditions

function validateEmail(email) {
    const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return regex.test(email);
}
console.log(validateEmail("test@example.com"));  // true

57. Sort the Array by Title and Display

let books = [
    { title: "JavaScript Basics", author: "John" },
    { title: "Advanced JS", author: "Jane" },
    { title: "HTML & CSS", author: "Jake" }
];
books.sort((a, b) => a.title.localeCompare(b.title));
console.log(books);

58. Check Whether a Given Number is Prime or Not

function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}
console.log(isPrime(7));  // true

59. Compute the Sum and Product of an Array of Integers

let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, num) => acc + num, 0);
let product = arr.reduce((acc, num) => acc * num, 1);
console.log(`Sum: ${sum}, Product: ${product}`);

60. Highlight Bold Words of Paragraph on Mouse Over

document.querySelectorAll("p b").forEach(boldWord => {
    boldWord.addEventListener("mouseover", () => {
        boldWord.style.color = "red";
    });
    boldWord.addEventListener("mouseout", () => {
        boldWord.style.color = "";
    });
});

61. Read Data from XML File and Print It in Tabular Manner

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        let parser = new DOMParser();
        let xmlDoc = parser.parseFromString(xhr.responseText, "text/xml");
        let rows = xmlDoc.getElementsByTagName("row");
        let table = "<table border='1'><tr><th>Name</th><th>Age</th></tr>";
        for (let i = 0; i < rows.length; i++) {
            let name = rows[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
            let age = rows[i].getElementsByTagName("age")[0].childNodes[0].nodeValue;
            table += `<tr><td>${name}</td><td>${age}</td></tr>`;
        }
        table += "</table>";
        document.body.innerHTML = table;
    }
};
xhr.send();

62. Using Events in JavaScript

document.getElementById("myButton").addEventListener("click", function() {
    alert("Button clicked!");
});

63. Check Whether a String Starts with 'java'

function checkString(str) {
    return str.startsWith("java");
}
console.log(checkString("javascript"));  // true

64. Using While Statement to Display 10 Numbers

let num = 1;
while (num <= 10) {
    console.log(num);
    num++;
}

65. Remove White Spaces from a Given String

function removeWhiteSpaces(str) {
    return str.replace(/\s+/g, '');
}
console.log(removeWhiteSpaces("Hello World! "));  // "HelloWorld!"

66. Accept a Number and Check Whether it is Prime

function checkPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return num > 1;
}
console.log(checkPrime(17));  // true

67. Find the Greatest of Three Given Numbers

function findGreatest(a, b, c) {
    return Math.max(a, b, c);
}
console.log(findGreatest(5, 10, 3));  // 10

68. Check Whether a Given Number is Armstrong or Not

function isArmstrong(num) {
    let sum = 0;
    let temp = num;
    let digits = num.toString().length;
    while (temp > 0) {
        let digit = temp % 10;
        sum += Math.pow(digit, digits);
        temp = Math.floor(temp / 10);
    }
    return sum === num;
}
console.log(isArmstrong(153));  // true

69. Design Simple Calculator

function simpleCalculator(a, b, operator) {
    switch (operator) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
        default: return "Invalid operator";
    }
}
console.log(simpleCalculator(4, 5, "+"));  // 9

70. Find Square and Cube of Number Using Function

function square(num) {
    return num * num;
}

function cube(num) {
    return num * num * num;
}

console.log(square(3));  // 9
console.log(cube(3));    // 27

71. Implement Array

let arr = [1, 2, 3, 4, 5];
arr.push(6);  // Add element to array
console.log(arr);  // [1, 2, 3, 4, 5, 6]

72. Find Closest Value to 100 from Two Numerical Values

function closestTo100(a, b) {
    return Math.abs(100 - a) < Math.abs(100 - b) ? a : b;
}
console.log(closestTo100(95, 105));  // 95

73. Check Whether a Given Number is Positive or Negative

function checkPositiveNegative(num) {
    return num >= 0 ? "Positive" : "Negative";
}
console.log(checkPositiveNegative(-5));  // Negative

74. Print the Fibonacci Sequence

function fibonacci(n) {
    let a = 0, b = 1;
    let result = [a, b];
    for (let i = 2; i < n; i++) {
        let next = a + b;
        result.push(next);
        a = b;
        b = next;
    }
    return result;
}
console.log(fibonacci(10));  // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

75. Using jQuery to Display Datepicker

$(document).ready(function() {
    $("#datepicker").datepicker();
});

76. Compute the Average Marks of Students

let studentsMarks = [90, 80, 70, 85, 95];
let total = studentsMarks.reduce((acc, mark) => acc + mark, 0);
let average = total / studentsMarks.length;
console.log(average);  // 84

77. Find the Greatest of Three Numbers

let a = 15, b = 30, c = 20;
console.log(Math.max(a, b, c));  // 30


78. Validate Classful IP Address in Network

A classful IP address is typically used in the older class-based addressing system, which divides IP addresses into classes (A, B, C, D, and E). We'll validate Class A, B, and C IP addresses, which are the most commonly used for public IP networks.

Class A: 0.0.0.0 to 127.255.255.255
Class B: 128.0.0.0 to 191.255.255.255
Class C: 192.0.0.0 to 223.255.255.255

Here's the JavaScript code to validate a classful IP address:

function validateClassfulIP(ip) {
    const regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    
    if (!regex.test(ip)) {
        return "Invalid IP address format";
    }
    
    const octets = ip.split('.').map(Number);
    
    // Check if it's a valid Class A, B, or C IP
    if (octets[0] >= 0 && octets[0] <= 127) {
        return "Class A IP Address";
    } else if (octets[0] >= 128 && octets[0] <= 191) {
        return "Class B IP Address";
    } else if (octets[0] >= 192 && octets[0] <= 223) {
        return "Class C IP Address";
    } else {
        return "IP Address outside Classful range";
    }
}

console.log(validateClassfulIP("192.168.1.1"));  // Class C IP Address
console.log(validateClassfulIP("150.50.100.25")); // Class B IP Address
console.log(validateClassfulIP("300.500.1.1"));  // Invalid IP address format

Explanation:

  • Regex validation: The regular expression checks if the IP address is in the correct format (x.x.x.x), where each x is between 0 and 255.

  • Class determination: Based on the first octet of the IP address, we determine whether it's a Class A, B, or C IP address.


79. Check Whether a Given Number is Armstrong or Not

function isArmstrong(num) {
    let sum = 0;
    let temp = num;
    let digits = num.toString().length;
    while (temp > 0) {
        let digit = temp % 10;
        sum += Math.pow(digit, digits);
        temp = Math.floor(temp / 10);
    }
    return sum === num;
}
console.log(isArmstrong(153));  // true

80. Get the Website URL

console.log(window.location.href);  // Get the current URL

81. Extract Values at Specific Indexes from a Specified Array

function extractValues(arr, indexes) {
    return indexes.map(index => arr[index]);
}
console.log(extractValues([1, 2, 3, 4], [0, 2]));  // [1, 3]

82. Validate Registration Page Using Regular Expression

function validateRegistrationForm(email, password) {
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
    return emailRegex.test(email) && passwordRegex.test(password);
}
console.log(validateRegistrationForm("test@example.com", "Password123"));  // true

83. Find Duplicate Values in an Array

function findDuplicates(arr) {
    let seen = new Set();
    let duplicates = [];
    for (let i = 0; i < arr.length; i++) {
        if (seen.has(arr[i])) {
            duplicates.push(arr[i]);
        } else {
            seen.add(arr[i]);
        }
    }
    return duplicates;
}
console.log(findDuplicates([1, 2, 3, 4, 1, 2]));  // [1, 2]

84. Demonstrate Arithmetic Operations Using Switch Case

function arithmeticOperation(a, b, operator) {
    switch (operator) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        default:
            return "Invalid operator";
    }
}
console.log(arithmeticOperation(10, 5, "+"));  // 15

85. Read Three Numbers and Output Their Average

function averageOfThreeNumbers(a, b, c) {
    return (a + b + c) / 3;
}
console.log(averageOfThreeNumbers(10, 20, 30));  // 20

86. Validate Login Form

function validateLoginForm(username, password) {
    return username.length > 0 && password.length > 5;
}
console.log(validateLoginForm("user", "123456"));  // true

87. Count the Number of Vowels in a Given String

function countVowels(str) {
    return str.match(/[aeiouAEIOU]/g) ? str.match(/[aeiouAEIOU]/g).length : 0;
}
console.log(countVowels("Hello World"));  // 3

88. Check if an Element Exists in an Array or Not

function elementExists(arr, element) {
    return arr.includes(element);
}
console.log(elementExists([1, 2, 3, 4], 3));  // true

89. Accept Two Numbers and Perform Addition by Using Mouseover Event

document.getElementById("addButton").addEventListener("mouseover", function() {
    let num1 = parseInt(document.getElementById("num1").value);
    let num2 = parseInt(document.getElementById("num2").value);
    let result = num1 + num2;
    document.getElementById("result").innerText = result;
});

90. Find the Kth Greatest Element in an Array

function kthGreatest(arr, k) {
    arr.sort((a, b) => b - a);
    return arr[k - 1];
}
console.log(kthGreatest([10, 20, 30, 40, 50], 3));  // 30

91. Create, Read, Update, and Delete Cookies

// Set a cookie
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2025 12:00:00 UTC";

// Get cookies
console.log(document.cookie);

// Update cookie
document.cookie = "username=JaneDoe; expires=Thu, 18 Dec 2025 12:00:00 UTC";

// Delete cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

92. Display Even Numbers from 1 to 10

for (let i = 2; i <= 10; i += 2) {
    console.log(i);
}

93. Find Sum of Two Numbers

function sum(a, b) {
    return a + b;
}
console.log(sum(3, 4));  // 7

94. Generate Multiplication Table of a Given Number

function multiplicationTable(num) {
    for (let i = 1; i <= 10; i++) {
        console.log(`${num} x ${i} = ${num * i}`);
    }
}
multiplicationTable(5);

95. Convert Celsius to Fahrenheit

function celsiusToFahrenheit(celsius) {
    return (celsius * 9/5) + 32;
}
console.log(celsiusToFahrenheit(25));  // 77

96. Merge Two Arrays and Remove Duplicate Items

function mergeAndRemoveDuplicates(arr1, arr2) {
    return [...new Set([...arr1, ...arr2])];
}
console.log(mergeAndRemoveDuplicates([1, 2, 3], [3, 4, 5]));  // [1, 2, 3, 4, 5]

97. Scroll Your Name in the Scrollbar

let marquee = document.createElement("marquee");
marquee.textContent = "Your Name";
document.body.appendChild(marquee);

98. Display Current Date and Time

let date = new Date();
console.log(date.toString());  // Current date and time

99. List the Properties of a JavaScript Object

let person = {
    name: "John",
    age: 30,
    country: "USA"
};
console.log(Object.keys(person));  // ['name', 'age', 'country']

100. Check Whether a Given String is Palindrome or Not

function isPalindrome(str) {
    let reversed = str.split("").reverse().join("");
    return str === reversed;
}
console.log(isPalindrome("racecar"));  // true



Post a Comment

0 Comments