JavaScript Programs for Beginners

Explore a collection of simple JavaScript programs that demonstrate key concepts like mathematical operations, string manipulations, and more. These programs are perfect for beginners to practice and understand JavaScript functionality.

 

1. JavaScript Program to Check Leap Year:

function isLeapYear(year) {
    if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
        return `${year} is a Leap Year.`;
    } else {
        return `${year} is not a Leap Year.`;
    }
}

console.log(isLeapYear(2024)); // Example usage

 

2. JavaScript Program to Convert Kilometers to Miles:

function kmToMiles(km) {
    const miles = km * 0.621371;
    return `${km} kilometers is equal to ${miles} miles.`;
}

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

 

3. JavaScript Program to Generate a Series of n Prime Numbers:

function generatePrimes(n) {
    let primes = [];
    for (let i = 2; primes.length < n; i++) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    return primes;

    function isPrime(num) {
        for (let j = 2; j <= Math.sqrt(num); j++) {
            if (num % j === 0) {
                return false;
            }
        }
        return num > 1;
    }
}

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

 

4. JavaScript Program to Display Multiplication Table:

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

multiplicationTable(5); // Example usage

 

5. JavaScript Program to Print Your Favourite Movie and Actor Name:

function printMovieDetails() {
    console.log("My favourite movie is 'Inception' and my favourite actor is 'Leonardo DiCaprio'.");
}

printMovieDetails(); // Example usage

 

6. JavaScript Program to Calculate the Days Left Before Christmas:

function daysUntilChristmas() {
    const today = new Date();
    const christmas = new Date(today.getFullYear(), 11, 25); // December 25th
    const timeDiff = christmas - today;
    const daysLeft = Math.ceil(timeDiff / (1000 * 3600 * 24));
    return `Days left before Christmas: ${daysLeft}`;
}

console.log(daysUntilChristmas()); // Example usage

 

7. JavaScript Program to Illustrate the Variable:

let message = "Hello, this is a JavaScript variable!";
console.log(message);

 

8. JavaScript Program to Find the Factorial of a Given Number:

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

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

 

9. JavaScript Program to Find the Factorial of a Number:

// Same as the previous factorial program
console.log(factorial(6)); // Example usage

 

10. JavaScript Program to Generate a Random Number:

function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(generateRandomNumber(1, 100)); // Example usage

 

11. JavaScript Program to Enter Temperature in Celsius and Convert It into Fahrenheit:

function celsiusToFahrenheit(celsius) {
    const fahrenheit = (celsius * 9/5) + 32;
    return `${celsius}°C is equal to ${fahrenheit}°F.`;
}

console.log(celsiusToFahrenheit(25)); // Example usage

 

12. JavaScript Program to Add Two Matrices Using Multi-Dimensional Arrays:

function addMatrices(matrix1, matrix2) {
    let result = [];
    for (let i = 0; i < matrix1.length; i++) {
        result[i] = [];
        for (let j = 0; j < matrix1[i].length; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return result;
}

let matrix1 = [[1, 2], [3, 4]];
let matrix2 = [[5, 6], [7, 8]];

console.log(addMatrices(matrix1, matrix2)); // Example usage

 

13. JavaScript Program to Find Whether a Number is Prime or Not:

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

 

14. JavaScript Program to Print the Reverse of a Number:

function reverseNumber(num) {
    let reversed = num.toString().split('').reverse().join('');
    return reversed;
}

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

 

15. JavaScript Program to Display Date and Time:

function displayDateTime() {
    const date = new Date();
    return `Current date and time: ${date.toLocaleString()}`;
}

console.log(displayDateTime()); // Example usage

 

16. JavaScript Program to Display Squares of 1 to 10 Numbers Using While Loop:

function displaySquares() {
    let i = 1;
    while (i <= 10) {
        console.log(`${i}^2 = ${i * i}`);
        i++;
    }
}

displaySquares(); // Example usage

 

17. JavaScript Program to Extract the First Half of an Even String:

function extractFirstHalf(str) {
    if (str.length % 2 === 0) {
        return str.substring(0, str.length / 2);
    } else {
        return "The string length is not even!";
    }
}

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

 

18. JavaScript Program to Validate Form Data Before Submission:

function validateForm() {
    const name = document.getElementById("name").value;
    if (name === "") {
        alert("Name must be filled out");
        return false;
    }
    return true;
}

 

19. JavaScript Program to Calculate Multiplication and Division of Two Numbers Input from User:

function calculate() {
    const num1 = parseFloat(prompt("Enter the first number:"));
    const num2 = parseFloat(prompt("Enter the second number:"));

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

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

calculate(); // Example usage

 

20. JavaScript Program to Accept a Number from User and Display its Multiplication Table:

function displayMultiplicationTable() {
    const number = prompt("Enter a number to display its multiplication table:");
    for (let i = 1; i <= 10; i++) {
        console.log(`${number} x ${i} = ${number * i}`);
    }
}

displayMultiplicationTable(); // Example usage

 

21. JavaScript Program to Validate Username and Password:

function validateLogin(username, password) {
    const correctUsername = "admin";
    const correctPassword = "1234";
    
    if (username === correctUsername && password === correctPassword) {
        return "Login Successful!";
    } else {
        return "Invalid Username or Password.";
    }
}

console.log(validateLogin("admin", "1234")); // Example usage

 

22. JavaScript Program to Find the Sum of n Natural Numbers:

function sumOfNaturalNumbers(n) {
    let sum = (n * (n + 1)) / 2;
    return `The sum of first ${n} natural numbers is: ${sum}`;
}

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

 

23. JavaScript Program to Find the Area of a Triangle:

function areaOfTriangle(base, height) {
    const area = (base * height) / 2;
    return `The area of the triangle is: ${area}`;
}

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

 

24. JavaScript Program to Strip Leading and Trailing Spaces from a String:

function stripSpaces(str) {
    return str.trim();
}

console.log(stripSpaces("   Hello, World!   ")); // Example usage

 

25. JavaScript Program to Illustrate super Keyword:

class Animal {
    speak() {
        return "Animal speaks";
    }
}

class Dog extends Animal {
    speak() {
        return super.speak() + " and Dog barks";
    }
}

const dog = new Dog();
console.log(dog.speak()); // Example usage

 

26. JavaScript Program to Implement a Toggle Switch that Changes its State When Clicked:

let isOn = false;

function toggleSwitch() {
    isOn = !isOn;
    console.log(isOn ? "The switch is ON" : "The switch is OFF");
}

toggleSwitch(); // Example usage
toggleSwitch(); // Example usage

 

27. JavaScript Program for Addition, Subtraction, Multiplication, and Division Functions:

function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
function divide(a, b) { return a / b; }

console.log(add(5, 3)); // Example usage
console.log(subtract(5, 3)); // Example usage
console.log(multiply(5, 3)); // Example usage
console.log(divide(5, 3)); // Example usage

 

28. JavaScript Program to Validate a Login Form:

function validateLoginForm() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;
    
    if (username === "" || password === "") {
        alert("Both fields are required!");
        return false;
    }
    return true;
}

 

29. JavaScript Program to Find the Area of a Triangle (Again):

// Same as program 23
console.log(areaOfTriangle(5, 6)); // Example usage

 

30. JavaScript Program to Sort the Data of an Array:

function sortArray(arr) {
    return arr.sort((a, b) => a - b);
}

console.log(sortArray([5, 2, 9, 1, 5, 6])); // Example usage

 

31. JavaScript Program that Will Remove the Duplicate Elements from an Array:

function removeDuplicates(arr) {
    return [...new Set(arr)];
}

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

 

32. JavaScript Program to Create an Array and Insert Data into Array:

let myArray = [];
myArray.push(1);
myArray.push(2);
myArray.push(3);

console.log(myArray); // Example usage

 

33. JavaScript Program to Add Digits of a Number:

function addDigits(num) {
    let sum = 0;
    while (num > 0) {
        sum += num % 10;
        num = Math.floor(num / 10);
    }
    return sum;
}

console.log(addDigits(123)); // Example usage

 

34. JavaScript Program to Display First Ten Even Numbers Using For Loop:

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

displayEvenNumbers(); // Example usage

 

35. JavaScript Program to Find the Area of a Triangle Where Three Sides are 5, 6, 7:

function areaOfTriangleBySides(a, b, c) {
    const s = (a + b + c) / 2;
    const area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
    return `The area of the triangle is: ${area}`;
}

console.log(areaOfTriangleBySides(5, 6, 7)); // Example usage

 

36. JavaScript Program to Change Color and Font Using Event Handling:

function changeStyle() {
    document.body.style.backgroundColor = "lightblue";
    document.body.style.fontFamily = "Arial, sans-serif";
}

document.getElementById("myButton").addEventListener("click", changeStyle);

 

37. JavaScript Program to Validate the Registration Page:

function validateRegistrationForm() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;
    
    if (username === "" || password === "") {
        alert("All fields are required!");
        return false;
    }
    return true;
}

 

38. JavaScript Program to Check if a Number is Positive, Negative, or Zero:

function checkNumber(num) {
    if (num > 0) {
        return "The number is positive.";
    } else if (num < 0) {
        return "The number is negative.";
    } else {
        return "The number is zero.";
    }
}

console.log(checkNumber(-5)); // Example usage

 

39. JavaScript Program to Accept Two Numbers and Perform Addition:

function addTwoNumbers() {
    const num1 = parseFloat(prompt("Enter the first number:"));
    const num2 = parseFloat(prompt("Enter the second number:"));
    
    const sum = num1 + num2;
    console.log(`The sum is: ${sum}`);
}

addTwoNumbers(); // Example usage

 

40. JavaScript Program to Redirect to a Specified URL:

function redirectToUrl(url) {
    window.location.href = url;
}

redirectToUrl("https://www.example.com"); // Example usage

 

41. JavaScript Program to Sort an Array of JavaScript Objects:

let people = [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 },
    { name: "Jack", age: 35 }
];

people.sort((a, b) => a.age - b.age);
console.log(people); // Example usage

 

42. JavaScript Program to Change Color and Font Using Event Handling (Again):

// Same as program 36

 

43. JavaScript Program to Get the Website URL (Loading Page):

function getWebsiteUrl() {
    return window.location.href;
}

console.log(getWebsiteUrl()); // Example usage

 

44. JavaScript Program for Validating Registration Form (Again):

// Same as program 37

 

45. JavaScript Program to Validate an Email Address:

function validateEmail(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email) ? "Valid email address" : "Invalid email address";
}

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

 

46. JavaScript Program to Display Digital Clock:

function displayClock() {
    const time = new Date();
    const hours = time.getHours();
    const minutes = time.getMinutes();
    const seconds = time.getSeconds();
    
    console.log(`${hours}:${minutes}:${seconds}`);
}

setInterval(displayClock, 1000); // Example usage

 

47. JavaScript Program to Implement Inheritance Concept:

class Animal {
    speak() {
        return "Animal speaks";
    }
}

class Dog extends Animal {
    speak() {
        return super.speak() + " and Dog barks";
    }
}

const dog = new Dog();
console.log(dog.speak()); // Example usage

 

48. JavaScript Program to Demonstrate Java Intrinsic Function:

// Example of intrinsic function in JavaScript
let number = 12345;
console.log(number.toString()); // Converts number to string

 

49. JavaScript Program to Display Table of Any Number:

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

displayTableOfNumber(7); // Example usage

 

50. JavaScript Program to Find the Fibonacci Series:

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

console.log(fibonacciSeries(10)); // Example usage, will print first 10 Fibonacci numbers


 

These JavaScript programs cover a variety of fundamental programming concepts and will help you get hands-on experience with loops, conditionals, user input, and more. Perfect for anyone starting with JavaScript!


Post a Comment

0 Comments