JavaScript All Exercises & Assignments

Write a JavaScript program to display Hello World

Description: Write a JavaScript program that prints “Hello, World!” in the console.

Hint:

  • Use console.log().
  • Text must be inside quotes.

JavaScript Hello World program

console.log("Hello, World!");

Output:

Tutorials Class - Output Window

Hello, World!

How it works

  • console.log() prints a message in the browser console (press F12 to open it).
  • The text is a string, so it is written in quotes.

Read JavaScript Basic Program.

Write a JavaScript program to add two numbers

Description: Store two numbers in variables and print their sum.

Hint:

  • Use let or const for the variables.
  • Use the + operator.

JavaScript program to add two numbers

const a = 12;
const b = 8;
const sum = a + b;

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output:

Tutorials Class - Output Window

Sum of 12 and 8 is 20

How it works

  • The + operator adds two numbers.
  • A template literal with ${ } puts the values inside the text.

Read JavaScript Operators. If the numbers come from prompt() or an input box, convert them with Number() first, otherwise "12" + "8" gives "128".

Write a JavaScript program to swap two variables

Description: Swap the values of two variables a and b.

Hint:

  • The old way uses a third variable.
  • The modern way uses array destructuring.

JavaScript program to swap two variables

let a = 10;
let b = 20;
console.log("Before:", a, b);

[a, b] = [b, a];

console.log("After:", a, b);

Output:

Tutorials Class - Output Window

Before: 10 20
After: 20 10

How it works

  • The right side [b, a] makes a new array with the two values.
  • The left side [a, b] destructures it back into the variables, so they are swapped in one line.

Read ES6 Features.

Write a JavaScript program to check even or odd number

Description: Check whether a number is even or odd.

Hint:

  • A number is even if the remainder after dividing by 2 is 0.

JavaScript program for even or odd

function checkEvenOdd(n) {
  if (n % 2 === 0) {
    return n + " is even";
  }
  return n + " is odd";
}

console.log(checkEvenOdd(4));
console.log(checkEvenOdd(7));

Output:

Tutorials Class - Output Window

4 is even
7 is odd

How it works

  • % gives the remainder: 4 % 2 is 0 and 7 % 2 is 1.
  • The function returns a text for each case.

Read Conditional Statements.

Write a JavaScript program to find the largest of three numbers

Description: Find the largest of the three numbers 25, 78 and 42.

Hint:

  • Compare with if and &&.
  • Or use Math.max().

JavaScript program for the largest of three numbers

const a = 25, b = 78, c = 42;

let largest;
if (a >= b && a >= c) {
  largest = a;
} else if (b >= a && b >= c) {
  largest = b;
} else {
  largest = c;
}

console.log("Largest:", largest);
console.log("Using Math.max:", Math.max(a, b, c));

Output:

Tutorials Class - Output Window

Largest: 78
Using Math.max: 78

How it works

  • The first if checks if a is at least as big as both others.
  • Math.max() does the same in one call.

Write a JavaScript program to check leap year

Description: Check if a year is a leap year.

Hint:

  • Divisible by 4 and not by 100, or divisible by 400.

JavaScript program to check a leap year

function isLeap(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

for (const y of [2024, 1900, 2000, 2023]) {
  console.log(y + (isLeap(y) ? " is a leap year" : " is not a leap year"));
}

Output:

Tutorials Class - Output Window

2024 is a leap year
1900 is not a leap year
2000 is a leap year
2023 is not a leap year

How it works

  • 1900 is divisible by 100 but not by 400, so it is not a leap year.
  • The ternary operator picks the text.

Write a JavaScript program to print the multiplication table of a number

Description: Print the multiplication table of 7, from 1 to 10.

Hint:

  • Use a for loop from 1 to 10.

JavaScript multiplication table program

const num = 7;

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

Output:

Tutorials Class - Output Window

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

How it works

  • The loop runs with i from 1 to 10.
  • The template literal prints the line with the numbers.

Read JavaScript Loops.

Write a JavaScript program to find the factorial of a number

Description: Find the factorial of 5 in two ways: with a loop and with a recursive function.

Hint:

  • Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
  • A recursive function needs a base case.

JavaScript factorial program

// loop
let fact = 1;
for (let i = 1; i <= 5; i++) {
  fact *= i;
}
console.log(fact);

// recursion
function factorial(n) {
  if (n <= 1) return 1;       // base case
  return n * factorial(n - 1);
}
console.log(factorial(5));

Output:

Tutorials Class - Output Window

120
120

How it works

  • The loop multiplies fact with 1, 2, 3, 4 and 5.
  • The recursive function calls itself with a smaller number until it reaches the base case.

Read JavaScript Functions.

Write a JavaScript program to print the Fibonacci series

Description: Print the first 10 numbers of the Fibonacci series.

Hint:

  • Each number is the sum of the two before it.
  • Start with 0 and 1.

JavaScript Fibonacci program

let a = 0, b = 1;
const series = [];

for (let i = 0; i < 10; i++) {
  series.push(a);
  [a, b] = [b, a + b];
}

console.log(series.join(", "));

Output:

Tutorials Class - Output Window

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

How it works

  • [a, b] = [b, a + b] moves to the next pair.
  • join(", ") makes one text from the array.

Write a JavaScript program to check prime number

Description: Check whether the numbers 2, 15, 17 and 1 are prime.

Hint:

  • A prime number is greater than 1 and has no divisor other than 1 and itself.
  • Test divisors up to the square root.

JavaScript prime number program

function isPrime(n) {
  if (n < 2) return false;
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) return false;
  }
  return true;
}

for (const n of [2, 15, 17, 1]) {
  console.log(n + (isPrime(n) ? " is prime" : " is not prime"));
}

Output:

Tutorials Class - Output Window

2 is prime
15 is not prime
17 is prime
1 is not prime

How it works

  • Numbers below 2 are not prime.
  • For 15 the loop finds that 15 % 3 === 0 and returns false.
  • As soon as one divisor is found, the function returns.

Write a JavaScript program to reverse a string

Description: Reverse the string “JavaScript”.

Hint:

  • Split the string into an array of characters, reverse it and join it back.

JavaScript program to reverse a string

const text = "JavaScript";

// 1. split, reverse, join
console.log(text.split("").reverse().join(""));

// 2. loop
let result = "";
for (const ch of text) {
  result = ch + result;
}
console.log(result);

Output:

Tutorials Class - Output Window

tpircSavaJ
tpircSavaJ

How it works

  • Strings cannot be reversed directly, because they have no reverse() method, but arrays do.
  • In the loop each new character is added to the front of the result.

Read JavaScript Strings.

Write a JavaScript program to check palindrome string

Description: Check if the words “madam”, “Level” and “hello” are palindromes.

Hint:

  • A palindrome reads the same backwards.
  • Change the text to lowercase first.

JavaScript palindrome program

function isPalindrome(text) {
  const clean = text.toLowerCase();
  return clean === clean.split("").reverse().join("");
}

for (const w of ["madam", "Level", "hello"]) {
  console.log(w + (isPalindrome(w) ? " is a palindrome" : " is not a palindrome"));
}

Output:

Tutorials Class - Output Window

madam is a palindrome
Level is a palindrome
hello is not a palindrome

How it works

  • toLowerCase() makes “Level” equal to “level”.
  • The text is compared with its reverse.

Write a JavaScript program to count vowels in a string

Description: Count the vowels in “Tutorials Class”.

Hint:

  • Vowels are a, e, i, o and u.
  • match() with the g flag returns all matches, or null if none.

JavaScript program to count vowels

const text = "Tutorials Class";
const matches = text.toLowerCase().match(/[aeiou]/g);

console.log("Vowels:", matches ? matches.length : 0);

Output:

Tutorials Class - Output Window

Vowels: 5

How it works

  • /[aeiou]/g finds every vowel.
  • If there is no vowel, match() returns null, so we check it first.

Read Regular Expressions.

Write a JavaScript program to find the sum and average of array elements

Description: Find the sum and the average of the array [10, 20, 30, 40].

Hint:

  • Use reduce() to add all items.
  • Average = sum / number of items.

JavaScript program for sum and average of an array

const numbers = [10, 20, 30, 40];

const sum = numbers.reduce((total, n) => total + n, 0);
const average = sum / numbers.length;

console.log("Sum:", sum);
console.log("Average:", average);

Output:

Tutorials Class - Output Window

Sum: 100
Average: 25

How it works

  • reduce() starts with 0 and adds each number.
  • The average is the sum divided by numbers.length.

Read Array Methods.

Write a JavaScript program to find the largest and smallest number in an array

Description: Find the largest and smallest number in [45, 12, 89, 3, 67].

Hint:

  • Math.max takes separate numbers, so spread the array with ....

JavaScript largest and smallest in an array

const numbers = [45, 12, 89, 3, 67];

console.log("Largest:", Math.max(...numbers));
console.log("Smallest:", Math.min(...numbers));

// with a loop
let max = numbers[0];
let min = numbers[0];
for (const n of numbers) {
  if (n > max) max = n;
  if (n < min) min = n;
}
console.log(max, min);

Output:

Tutorials Class - Output Window

Largest: 89
Smallest: 3
89 3

How it works

  • ...numbers spreads the array into separate arguments.
  • The loop keeps the biggest and smallest value seen so far.

Write a JavaScript program to remove duplicates from an array

Description: Remove the duplicates from [1, 2, 2, 3, 4, 4, 5].

Hint:

  • A Set keeps only unique values.

JavaScript program to remove duplicates

const items = [1, 2, 2, 3, 4, 4, 5];

const unique = [...new Set(items)];
console.log(unique);

const unique2 = items.filter((x, index) => items.indexOf(x) === index);
console.log(unique2);

Output:

Tutorials Class - Output Window

[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

How it works

  • new Set(items) removes duplicates, and [...set] turns it back to an array.
  • The second way keeps an item only if its first position is the current position.

Read Map and Set.

Write a JavaScript program to filter even numbers and double them

Description: From [1, 2, 3, 4, 5, 6] keep only the even numbers and double each one.

Hint:

  • Use filter() first, then map().

JavaScript filter and map program

const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers
  .filter(n => n % 2 === 0)
  .map(n => n * 2);

console.log(result);

Output:

Tutorials Class - Output Window

[ 4, 8, 12 ]

How it works

  • filter() keeps 2, 4 and 6.
  • map() doubles them to 4, 8 and 12.

Read Array Methods.

Write a JavaScript program to count the frequency of words in a sentence

Description: Count each word of the sentence “to be or not to be”.

Hint:

  • Split the sentence into words.
  • Use an object where the word is the key and the count is the value.

JavaScript word frequency program

const sentence = "to be or not to be";
const counts = {};

for (const word of sentence.split(" ")) {
  counts[word] = (counts[word] || 0) + 1;
}

console.log(counts);

Output:

Tutorials Class - Output Window

{ to: 2, be: 2, or: 1, not: 1 }

How it works

  • counts[word] || 0 gives 0 for a new word, and then 1 is added.
  • Objects keep the order in which keys were added.

Write a JavaScript program to change the text of a paragraph on button click

Description: Create a button. When the visitor clicks it, the text of a paragraph changes.

Hint:

  • Select both elements with getElementById().
  • Add a click listener to the button.

Change the text on button click

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Change text</title>
</head>
<body>
  <p id="message">Old text</p>
  <button id="btn">Change text</button>

  <script>
    const message = document.getElementById("message");
    const btn = document.getElementById("btn");

    btn.addEventListener("click", () => {
      message.textContent = "The text was changed!";
    });
  </script>
</body>
</html>

Output:

Output in the browser

The text was changed!

How it works

  • The result shown here is the page after the click. At the start it shows “Old text”.
  • textContent changes the text of the paragraph, and the page does not reload.

Read HTML DOM and DOM EventListener.

Write a JavaScript program to switch dark mode on and off

Description: Create a button that switches the page between light and dark colours.

Hint:

  • Make a CSS class .dark with dark colours.
  • Use classList.toggle("dark") on the body.

Toggle dark mode

<style>
  body { background: white; color: black; }
  body.dark { background: #1e1e1e; color: #f5f5f5; }
</style>

<button id="toggle">Toggle dark mode</button>

<script>
  document.getElementById("toggle").addEventListener("click", () => {
    document.body.classList.toggle("dark");
  });
</script>

Output:

Output in the browser

The page after one click (dark class added).

How it works

  • classList.toggle("dark") adds the class if it is missing, and removes it if it is there.
  • The CSS rule body.dark then changes the colours. Each click switches again.
  • The box above shows the dark state.

Read HTML DOM and CSS Variables.