JavaScript Programs for Beginners

Here are the JavaScript programs

 

51. JavaScript Program to Print Numbers from 10 to 20 Using For Loop:

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

 

52. JavaScript Program to Calculate Multiplication and Division of Two Numbers (Input from User):

let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));

let multiplication = num1 * num2;
let division = num1 / num2;

console.log(`Multiplication: ${multiplication}`);
console.log(`Division: ${division}`);

 

53. JavaScript Program to Validate User Accounts for Multiple Set of User ID and Password:

let users = [
    { username: 'user1', password: 'pass1' },
    { username: 'user2', password: 'pass2' },
    { username: 'user3', password: 'pass3' }
];

function validateAccount(username, password) {
    let user = users.find(u => u.username === username && u.password === password);
    return user ? 'Login successful!' : 'Invalid username or password.';
}

console.log(validateAccount('user2', 'pass2')); // Example usage

 

54. JavaScript Program to Remove HTML/XML Tags from String:

function removeHTMLTags(str) {
    return str.replace(/<[^>]*>/g, '');
}

console.log(removeHTMLTags("<div>Hello, <b>world</b>!</div>")); // Example usage

 

55. JavaScript Program to Find the Second Largest Number in an Array:

function findSecondLargest(arr) {
    let uniqueArr = [...new Set(arr)].sort((a, b) => a - b);
    return uniqueArr[uniqueArr.length - 2];
}

console.log(findSecondLargest([1, 3, 4, 2, 3, 5])); // Example usage

 

56. JavaScript Program to Generate Fibonacci Series Using Loop:

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(10)); // Example usage

 

57. JavaScript Program to Demonstrate Various Mouse Events with Output:

document.getElementById("myDiv").addEventListener("click", function() {
    console.log("Mouse clicked!");
});

document.getElementById("myDiv").addEventListener("mouseover", function() {
    console.log("Mouse over the div!");
});

 

58. JavaScript Program to Print Numbers from 1 to 20:

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

 

59. JavaScript Program to Reverse a String Using For Loop:

function reverseString(str) {
    let reversed = '';
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
}

console.log(reverseString("hello")); // Example usage

 

60. JavaScript Program to Print Current Date and Time:

function displayDateTime() {
    let currentDate = new Date();
    console.log(currentDate.toLocaleString());
}

displayDateTime(); // Example usage

 

61. JavaScript Program to Create Table with Two Columns Using Switch Statement:

function createTable(rows) {
    let table = "<table>";
    for (let i = 1; i <= rows; i++) {
        table += `<tr><td>Row ${i}</td><td>Data ${i}</td></tr>`;
    }
    table += "</table>";
    return table;
}

document.getElementById("table").innerHTML = createTable(5); // Example usage

 

62. JavaScript Program to Check if a 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)); // Example usage

 

63. JavaScript Program to Print Numbers from 10 to 20 Using For Loop (Again):

// Same as program 51

 

64. JavaScript Program to Demonstrate Multiplication Table:

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

multiplicationTable(5); // Example usage

 

65. JavaScript Program to Sum 3 and 5 Multiples Under 1000:

let sum = 0;
for (let i = 1; i < 1000; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
    }
}
console.log(sum);

 

66. JavaScript Program to Display Even Numbers from 25 to 50:

for (let i = 25; i <= 50; i++) {
    if (i % 2 === 0) {
        console.log(i);
    }
}

 

67. JavaScript Program to Perform Basic Arithmetic Operations:

function basicArithmetic(num1, num2) {
    console.log(`Addition: ${num1 + num2}`);
    console.log(`Subtraction: ${num1 - num2}`);
    console.log(`Multiplication: ${num1 * num2}`);
    console.log(`Division: ${num1 / num2}`);
}

basicArithmetic(10, 5); // Example usage

 

68. JavaScript Program to Calculate the Factorial of a Given Number:

function factorial(n) {
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

console.log(factorial(5)); // Example usage

 

69. JavaScript Program to Accept Two Numbers and Perform Addition of Two Numbers:

let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));

let sum = num1 + num2;
console.log(`Sum: ${sum}`);

 

70. JavaScript Program to Develop a Digital Clock to Display the Time and Set the Timer:

function startClock() {
    setInterval(() => {
        let time = new Date();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        let currentTime = `${hours}:${minutes}:${seconds}`;
        console.log(currentTime);
    }, 1000);
}

startClock(); // Example usage

 

71. JavaScript Program to Reverse a String:

function reverseString(str) {
    return str.split('').reverse().join('');
}

console.log(reverseString("hello")); // Example usage

 

72. JavaScript Program to Display the Current Date and Time (Again):

// Same as program 60

 

73. JavaScript Program to Calculate Volume of a Sphere:

function volumeOfSphere(radius) {
    return (4 / 3) * Math.PI * Math.pow(radius, 3);
}

console.log(volumeOfSphere(5)); // Example usage

 

74. JavaScript Program to Reverse a Number:

function reverseNumber(num) {
    let reversed = 0;
    while (num !== 0) {
        reversed = reversed * 10 + (num % 10);
        num = Math.floor(num / 10);
    }
    return reversed;
}

console.log(reverseNumber(12345)); // Example usage

 

75. JavaScript Program to Add Items in a Blank Array and Display the Items:

let arr = [];
arr.push(10);
arr.push(20);
arr.push(30);
console.log(arr);

 

76. JavaScript Program to Swap Pairs of Adjacent Digits of a Given Integer of Even Length:

function swapAdjacentDigits(num) {
    let numStr = num.toString();
    let swapped = '';
    for (let i = 0; i < numStr.length; i += 2) {
        swapped += numStr[i + 1] + numStr[i];
    }
    return swapped;
}

console.log(swapAdjacentDigits(123456)); // Example usage

 

77. JavaScript Program to Explain the Different Ways for Displaying Output:

// Using console.log()
console.log("Hello, world!");

// Using alert()
alert("This is an alert!");

// Using document.write()
document.write("This is written directly on the page.");

 

78. JavaScript Program to Sort an Array in Ascending Order:

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

 

79. JavaScript Program to Display the Greatest Number Among Three Numbers:

function greatestNumber(a, b, c) {
    return Math.max(a, b, c);
}

console.log(greatestNumber(5, 10, 7)); // Example usage
``

`

 

80. JavaScript Program to Validate Email ID of the User Using Regular Expression:

function validateEmail(email) {
    const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return regex.test(email);
}

console.log(validateEmail("test@example.com")); // Example usage

 

81. JavaScript Program for Addition of Two Numbers:

function addNumbers(a, b) {
    return a + b;
}

console.log(addNumbers(5, 10)); // Example usage

 

82. JavaScript Program to Get the Integers in Range (x, y):

function getRange(x, y) {
    let range = [];
    for (let i = x; i <= y; i++) {
        range.push(i);
    }
    return range;
}

console.log(getRange(5, 10)); // Example usage

 

83. JavaScript Program to Implement JavaScript Object Concept:

let person = {
    name: "John",
    age: 30,
    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
};

person.greet();

 

84. JavaScript Program to Change the Background Color After Clicking "Change Color" Button:

document.getElementById("changeColorBtn").addEventListener("click", function() {
    document.body.style.backgroundColor = "lightblue";
});

 

85. JavaScript Program to Remove Duplicate Items from an Array:

let arr = [1, 2, 3, 4, 1, 5, 2];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);

 

86. JavaScript Program to Remove Duplicate Items from an Array Ignoring Case Sensitivity:

let arr = ['apple', 'banana', 'Apple', 'Banana'];
let uniqueArr = [...new Set(arr.map(item => item.toLowerCase()))];
console.log(uniqueArr);

 

87. JavaScript Program to Accept String and Calculate Its Length:

let str = prompt("Enter a string:");
console.log(`Length of the string is: ${str.length}`);

 

88. JavaScript Program to Find the Area of a Rectangle:

function areaOfRectangle(length, width) {
    return length * width;
}

console.log(areaOfRectangle(5, 10)); // Example usage

 

89. JavaScript Program to Print First n Odd Numbers Divisible by 7:

function oddNumbersDivisibleBy7(n) {
    let count = 0;
    let num = 1;
    while (count < n) {
        if (num % 2 !== 0 && num % 7 === 0) {
            console.log(num);
            count++;
        }
        num++;
    }
}

oddNumbersDivisibleBy7(5); // Example usage

 

90. JavaScript Program to Accept a Number from User and Check Whether It Is Armstrong or Not:

function isArmstrong(num) {
    let numStr = num.toString();
    let length = numStr.length;
    let sum = 0;
    for (let i = 0; i < length; i++) {
        sum += Math.pow(parseInt(numStr[i]), length);
    }
    return sum === num;
}

console.log(isArmstrong(153)); // Example usage

 

91. JavaScript Program to Calculate Simple Interest:

function calculateSimpleInterest(principal, rate, time) {
    return (principal * rate * time) / 100;
}

console.log(calculateSimpleInterest(1000, 5, 2)); // Example usage

 

92. JavaScript Program Using If-Else Statement to Check if a Given Number is Even or Odd:

let num = parseInt(prompt("Enter a number:"));
if (num % 2 === 0) {
    console.log("Even");
} else {
    console.log("Odd");
}

 

93. JavaScript Program to Convert Dollar to Rupee:

function convertDollarToRupee(dollar) {
    const rate = 74.5; // Example rate of 1 USD = 74.5 INR
    return dollar * rate;
}

console.log(convertDollarToRupee(10)); // Example usage

 

94. JavaScript Program to Swap Two Numbers Using Functions:

function swapNumbers(a, b) {
    let temp = a;
    a = b;
    b = temp;
    return [a, b];
}

console.log(swapNumbers(5, 10)); // Example usage

 

95. JavaScript Program to Find the Area of a Circle:

function areaOfCircle(radius) {
    return Math.PI * radius * radius;
}

console.log(areaOfCircle(5)); // Example usage

 

96. JavaScript Program to Add Two Numbers Using Function:

function addTwoNumbers(a, b) {
    return a + b;
}

console.log(addTwoNumbers(5, 10)); // Example usage

 

97. JavaScript Program to Make a Simple Calculator:

function calculator(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(calculator(10, 5, "+")); // Example usage

 

98. JavaScript Program to Set the Background Color of a Paragraph:

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

 

99. JavaScript Program to Check if a Number is Prime or Not (Again):

// Same as program 62

 

100. JavaScript Program to Find Factorial of a Number in HTML:

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

 

These are JavaScript programs, you can use and modify them as needed for different purposes!


Post a Comment

0 Comments