50 JavaScript exercises along with their solutions:
Exercise 1:
Write a program to display “Hello, World!” in the console.
console.log("Hello, World!");
Exercise 2:
Write a program to add two numbers and display the result.
let num1 = 5;
let num2 = 10;
let sum = num1 + num2;
console.log(sum);
Exercise 3:
Write a program to check if a number is positive, negative, or zero.
let number = 0;
if (number > 0) {
console.log("Positive");
} else if (number < 0) {
console.log("Negative");
} else {
console.log("Zero");
}
Exercise 4:
Write a program to check if a number is even or odd.
let number = 7;
if (number % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
Exercise 5:
Write a program to find the maximum of two numbers.
let num1 = 10;
let num2 = 5;
let max = num1 > num2 ? num1 : num2;
console.log(max);
Exercise 6:
Write a program to find the minimum of two numbers.
let num1 = 10;
let num2 = 5;
let min = num1 < num2 ? num1 : num2;
console.log(min);
Exercise 7:
Write a program to check if a year is a leap year.
let year = 2020;
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log("Leap year");
} else {
console.log("Not a leap year");
}
Exercise 8:
Write a program to check if a string is empty or not.
let str = "";
if (str === "") {
console.log("String is empty");
} else {
console.log("String is not empty");
}
Exercise 9:
Write a program to check if a string is a palindrome.
let str = "madam";
let reversedStr = str.split("").reverse().join("");
if (str === reversedStr) {
console.log("Palindrome");
} else {
console.log("Not a palindrome");
}
Exercise 10:
Write a program to reverse a string.
let str = "Hello, World!";
let reversedStr = str.split("").reverse().join("");
console.log(reversedStr);
Exercise 11:
Write a program to find the factorial of a number.
let num = 5;
let factorial = 1;
for (let i = 1; i <= num; i++) {
factorial *= i;
}
console.log(factorial);
Exercise 12:
Write a program to generate Fibonacci series up to a given number of terms.
let numTerms = 10;
let fibonacciSeries = [0, 1];
for (let i = 2; i < numTerms; i++) {
let nextTerm = fibonacciSeries[i - 1] + fibonacciSeries[i - 2];
fibonacciSeries.push(nextTerm);
}
console.log(fibonacciSeries);
Exercise 13:
Write a program to check if a number is a prime number.
let num = 17;
let isPrime = true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i ===
0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log("Prime number");
} else {
console.log("Not a prime number");
}
Exercise 14:
Write a program to find the sum of all elements in an array.
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
Exercise 15:
Write a program to find the maximum element in an array.
let numbers = [1, 5, 3, 9, 2];
let max = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
console.log(max);
Exercise 16:
Write a program to remove duplicate elements from an array.
let numbers = [1, 2, 3, 2, 4, 1, 5, 4];
let uniqueNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (!uniqueNumbers.includes(numbers[i])) {
uniqueNumbers.push(numbers[i]);
}
}
console.log(uniqueNumbers);
Exercise 17:
Write a program to count the number of vowels in a string.
let str = "Hello, World!";
let vowels = ["a", "e", "i", "o", "u"];
let count = 0;
for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i].toLowerCase())) {
count++;
}
}
console.log(count);
Exercise 18:
Write a program to count the number of words in a string.
let str = "Hello, World!";
let words = str.split(" ");
let count = words.length;
console.log(count);
Exercise 19:
Write a program to check if a string is a valid email address.
let email = "test@example.com";
let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (regex.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
Exercise 20:
Write a program to reverse the order of words in a string.
let str = "Hello, World!";
let reversedWords = str.split(" ").reverse().join(" ");
console.log(reversedWords);
Exercise 21:
Write a program to find the length of the longest word in a string.
let str = "Hello, World!";
let words = str.split(" ");
let maxLength = 0;
for (let i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
console.log(maxLength);
Exercise 22:
Write a program to sort an array of numbers in ascending order.
let numbers = [5, 2, 9, 1, 7];
numbers.sort((a, b) => a - b);
console.log(numbers);
Exercise 23:
Write a program to sort an array of strings in alphabetical order.
let fruits = ["Apple", "Orange", "Banana", "Mango"];
fruits.sort();
console.log(fruits);
Exercise 24:
Write a program to check if two strings are an
agrams.
let str1 = "listen";
let str2 = "silent";
let sortedStr1 = str1.toLowerCase().split("").sort().join("");
let sortedStr2 = str2.toLowerCase().split("").sort().join("");
if (sortedStr1 === sortedStr2) {
console.log("Anagrams");
} else {
console.log("Not anagrams");
}
Exercise 25:
Write a program to find the sum of natural numbers up to a given number.
let num = 10;
let sum = 0;
for (let i = 1; i <= num; i++) {
sum += i;
}
console.log(sum);
Exercise 26:
Write a program to find the factorial of a number using recursion.
function factorial(num) {
if (num === 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
console.log(factorial(5));
Exercise 27:
Write a program to check if a string is a valid palindrome ignoring spaces and punctuation.
function isPalindrome(str) {
let regex = /[^\w]|_/g;
let cleanedStr = str.toLowerCase().replace(regex, "");
let reversedStr = cleanedStr.split("").reverse().join("");
return cleanedStr === reversedStr;
}
console.log(isPalindrome("A man, a plan, a canal, Panama!"));
Exercise 28:
Write a program to convert a string to title case.
function toTitleCase(str) {
let words = str.split(" ");
let titleCaseWords = [];
for (let i = 0; i < words.length; i++) {
let word = words[i];
let titleCaseWord = word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
titleCaseWords.push(titleCaseWord);
}
return titleCaseWords.join(" ");
}
console.log(toTitleCase("hello, world!"));
Exercise 29:
Write a program to find the second largest element in an array.
let numbers = [5, 2, 9, 1, 7];
numbers.sort((a, b) => b - a);
console.log(numbers[1]);
Exercise 30:
Write a program to remove all falsy values from an array.
let array = [0, 1, false, true, "", "hello", null, undefined, NaN];
let filteredArray = array.filter(Boolean);
console.log(filteredArray);
Exercise 31:
Write a program to find the median of an array of numbers.
let numbers = [5, 2, 9, 1, 7];
numbers.sort((a, b) => a - b);
let median;
if (numbers.length % 2 === 0) {
let midIndex = numbers.length / 2;
median = (numbers[midIndex - 1] + numbers[midIndex]) / 2;
} else {
let midIndex = Math.floor(numbers.length / 2);
median = numbers[midIndex];
}
console.log(median);
Exercise 32:
Write a program to find the sum of all even numbers in an array.
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
sum += numbers[i];
}
}
console.log(sum);
Exercise 33:
Write a program to find the intersection of two arrays
.
let array1 = [1, 2, 3, 4, 5];
let array2 = [4, 5, 6, 7, 8];
let intersection = [];
for (let i = 0; i < array1.length; i++) {
if (array2.includes(array1[i])) {
intersection.push(array1[i]);
}
}
console.log(intersection);
Exercise 34:
Write a program to convert a number to binary.
let num = 10;
let binary = num.toString(2);
console.log(binary);
Exercise 35:
Write a program to convert a binary number to decimal.
let binary = "1010";
let decimal = parseInt(binary, 2);
console.log(decimal);
Exercise 36:
Write a program to find the sum of digits of a number.
let num = 12345;
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);
Exercise 37:
Write a program to find the largest element in an array using reduce() method.
let numbers = [5, 2, 9, 1, 7];
let max = numbers.reduce((a, b) => Math.max(a, b));
console.log(max);
Exercise 38:
Write a program to find the smallest element in an array using reduce() method.
let numbers = [5, 2, 9, 1, 7];
let min = numbers.reduce((a, b) => Math.min(a, b));
console.log(min);
Exercise 39:
Write a program to remove duplicate elements from an array using the filter() method.
let numbers = [1, 2, 3, 2, 4, 1, 5, 4];
let uniqueNumbers = numbers.filter((value, index, array) => array.indexOf(value) === index);
console.log(uniqueNumbers);
Exercise 40:
Write a program to find the average of numbers in an array.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((a, b) => a + b);
let average = sum / numbers.length;
console.log(average);
Exercise 41:
Write a program to shuffle an array.
let array = [1, 2, 3, 4, 5];
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
console.log(array);
Exercise 42:
Write a program to find the number of occurrences of a specific element in an array.
let array = [1, 2, 3, 2, 4, 1, 5, 4];
let element = 2;
let count = array.reduce((acc, value) => (value === element ? acc + 1 : acc), 0);
console.log(count);
Exercise 43:
Write a program to check if a number is a perfect number.
function isPerfectNumber(num) {
let sum = 0;
for (let i = 1; i < num; i++) {
if (num % i === 0) {
sum += i;
}
}
return sum === num;
}
console.log(is
PerfectNumber(28));
Exercise 44:
Write a program to find the power of a number.
function power(base, exponent) {
let result = 1;
for (let i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
console.log(power(2, 3));
Exercise 45:
Write a program to find the number of words in a sentence.
let sentence = "Hello, World!";
let words = sentence.split(" ");
let count = words.length;
console.log(count);
Exercise 46:
Write a program to find the sum of digits of a number using recursion.
function sumOfDigits(num) {
if (num === 0) {
return 0;
} else {
return (num % 10) + sumOfDigits(Math.floor(num / 10));
}
}
console.log(sumOfDigits(12345));
Exercise 47:
Write a program to find the GCD (Greatest Common Divisor) of two numbers.
function gcd(a, b) {
if (b === 0) {
return a;
} else {
return gcd(b, a % b);
}
}
console.log(gcd(12, 18));
Exercise 48:
Write a program to convert a decimal number to binary using recursion.
function decimalToBinary(num) {
if (num === 0) {
return "";
} else {
return decimalToBinary(Math.floor(num / 2)) + (num % 2);
}
}
console.log(decimalToBinary(10));
Exercise 49:
Write a program to find the LCM (Least Common Multiple) of two numbers.
function lcm(a, b) {
let max = Math.max(a, b);
let min = Math.min(a, b);
for (let i = max; ; i += max) {
if (i % min === 0) {
return i;
}
}
}
console.log(lcm(12, 18));
Exercise 50:
Write a program to find the number of digits in a number.
let num = 12345;
let count = num.toString().length;
console.log(count);