JavaScript is one of the most versatile and widely used programming languages. For both beginners and experienced developers, solving coding problems is crucial to mastering the language. These challenges improve problem-solving skills and coding efficiency.
This article will explore 10 common JavaScript coding challenges that every developer should tackle. Whether you’re looking to test your knowledge or strengthen your skills, these problems will give you the hands-on practice you need to grow as a JavaScript programmer.
So, grab your favorite code editor, and let’s dive into these challenges to elevate your JavaScript game!
1. Palindrome Checker
How to write a function to check if a given string is a palindrome (the same forward and backward).
function isPalindrome(str) {
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleanStr === cleanStr.split('').reverse().join('');
}
2. Largest Number in an Array
Write a function how to find the largest number in an array.
function findLargestNumber(arr) {
return Math.max(...arr);
}
3. FizzBuzz
Write a FizzBuzz function that prints numbers from 1 to 100. But for multiples of 3, print “Fizz”; for multiples of 5, print “Buzz”; and for multiples of both, print “FizzBuzz”.
function fizzBuzz() {
for (let i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log('FizzBuzz');
else if (i % 3 === 0) console.log('Fizz');
else if (i % 5 === 0) console.log('Buzz');
else console.log(i);
}
}
4. Reverse a String
Write a function that takes a string and returns it reversed.
function reverseString(str) {
return str.split('').reverse().join('');
}
5. Remove Duplicates from an Array
Write a function that removes duplicate values from an array.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
6. Find the Sum of an Array
Write a function to calculate the sum of all numbers in an array.
function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
7. Flatten a Nested Array
Write a function that flattens a deeply nested array.
function flattenArray(arr) {
return arr.flat(Infinity);
}
8. Anagram Checker
Write a function that checks if two strings are anagrams of each other.
function isAnagram(str1, str2) {
const format = str => str.toLowerCase().replace(/[^a-z0-9]/g, '').split('').sort().join('');
return format(str1) === format(str2);
}
9. Find the Missing Number
Given an array of numbers 1 to n
with one missing number, find the missing number.
function findMissingNumber(arr, n) {
const expectedSum = (n * (n + 1)) / 2;
const actualSum = arr.reduce((sum, num) => sum + num, 0);
return expectedSum - actualSum;
}
10. Factorial of a Number
Write a function that returns the factorial of a given number.
function factorial(num) {
if (num === 0) return 1;
return num * factorial(num - 1);
}
These are the most common JavaScript problems which you should know.
If you want to practice more javascript challenges you can visit our website https://codeymaze.com/