JavaScript Top Exercises
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:
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 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:
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 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:
120
120
How it works
- The loop multiplies
factwith 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:
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:
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 === 0and returnsfalse. - 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:
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:
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 remove duplicates from an array
Description: Remove the duplicates from [1, 2, 2, 3, 4, 4, 5].
Hint:
- A
Setkeeps 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:
[ 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 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
clicklistener 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:
The text was changed!
How it works
- The result shown here is the page after the click. At the start it shows “Old text”.
textContentchanges the text of the paragraph, and the page does not reload.
Read HTML DOM and DOM EventListener.