Top 10 JavaScript Coding Challenges You Must Absolutely Know
Challenge 1: FizzBuzz
The FizzBuzz challenge is one of the most popular coding challenges that interviewers ask candidates. The problem is simple: write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number, and for multiples of five, print “Buzz”. For numbers that are multiples of both three and five, print “FizzBuzz”.
Here’s a potential solution:
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
}
Here’s how it works:
- The function takes an input parameter
n
, which is the highest number in the sequence to be printed. - It uses a
for
loop to iterate through each number in the sequence, starting from 1 and ending atn
. - For each number, it first checks if the number is divisible by both 3 and 5. If so, it prints the string “FizzBuzz” to the console.
- If the number is not divisible by both 3 and 5, it then checks if the number is divisible by 3. If so, it prints the string “Fizz” to the console.
- If the number is not divisible by both 3 and 5, and also not divisible by 3, it then checks if the number is divisible by 5. If so, it prints the string “Buzz” to the console.
- If the number is not divisible by either 3 or 5, it simply prints the number to the console.
By using these conditional checks, the fizzBuzz
function produces a sequence of numbers and strings that follow a specific pattern based on their divisibility by 3 and 5.
Here’s an example of usage:
fizzBuzz(4);
// 1
// 2
// Fizz
// 4
Challenge 2: Palindrome Checker
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. In this challenge, you need to write a function that checks whether a given string is a palindrome or not.
Here’s a potential solution:
function isPalindrome(str) {
const len = Math.floor(str.length / 2);
for (let i = 0; i < len; i++) {
if (str[i] !== str[str.length - i - 1]) {
return false;
}
}
return true;
}
The function first calculates the half-length of the input string by dividing its length by two and rounding down to the nearest integer using the Math.floor() function. This is because only half of the string needs to be checked since the other half is a mirror image of the first half in a palindrome.
Next, the function runs a for loop from the start of the string up to the halfway point, checking whether each character at the current index is equal to the corresponding character on the other half of the string, starting from the end. If at any point, the characters are not equal, the function returns false since the string is not a palindrome.
If the for loop completes without returning false, the function returns true since the string is a palindrome.
Here’s an example:
isPalindrome("racecar") // true
isPalindrome("hello") // false
Challenge 3: Reverse a String
In this challenge, you need to write a function that takes a string as an input and returns the string in reverse order.
Here’s a potential solution:
function reverseString(str) {
let reversedStr = "";
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
This function takes a string str
as an input and initializes an empty string reversedStr
. It then uses a for
loop to iterate over the characters in the input string in reverse order and concatenates each character to the reversedStr
variable. Finally, it returns the reversed string.
You can call this function like so:
const myString = "Hello, world!";
const reversedString = reverseString(myString);
console.log(reversedString); // Output: "!dlrow ,olleH"
Challenge 4: Sorting Algorithms
Sorting algorithms are an essential part of computer science, and in this challenge, you need to implement a sorting algorithm of your choice in JavaScript.
Here’s a potential solution:
function bubbleSort(array) {
const length = array.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - 1; j++) {
if (array[j] > array[j + 1]) {
const temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
This function takes an array as input and sorts it in ascending order using the bubble sort algorithm. The outer loop iterates through each element in the array, while the inner loop compares adjacent elements and swaps them if they are in the wrong order. The process repeats until no more swaps are needed, indicating that the array is sorted. Finally, the sorted array is returned.
const unsortedArray = [6, 2, 9, 12, 5];
const sortedArray = bubbleSort(unsortedArray);
console.log(sortedArray); // Output: [2, 5, 6, 9, 12]
In this example, we first define an unsorted array [6, 2, 9, 12, 5]
. We then call the bubbleSort
function and pass the unsorted array as an argument. The function sorts the array in ascending order using the bubble sort algorithm and returns the sorted array [2, 5, 6, 9, 12]
. Finally, we log the sorted array to the console using console.log
.
Challenge 5: Sum of Two
In this challenge, you need to write a function that takes two arrays of integers as input and finds a pair of numbers (one from each array) whose sum is equal to a given target number.
Here’s a potential solution:
function findPairWithSum(arr1, arr2, target) {
let hash = {};
for (let i = 0; i < arr1.length; i++) {
hash[arr1[i]] = true;
}
for (let i = 0; i < arr2.length; i++) {
let complement = target - arr2[i];
if (hash[complement]) {
return [complement, arr2[i]];
}
}
return null;
}
This function uses a hash table (implemented as a JavaScript object) to store the values in the first array, then loops over the second array and checks if the complement of each value (i.e., the difference between the target and the current value) is in the hash table. If it is, the function returns the pair of values. If no such pair is found, the function returns null
.
Here’s an example of how to use this function:
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let target = 9;
let pair = findPairWithSum(arr1, arr2, target);
console.log(pair); // Output: [5, 4]
Challenge 6: Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. In this challenge, you need to write a function that generates the Fibonacci sequence up to a given number.
Here’s a potential solution:
function generateFibonacciSequence(limit) {
let sequence = [0, 1];
while (sequence[sequence.length - 1] < limit) {
let nextNum = sequence[sequence.length - 1] + sequence[sequence.length - 2];
sequence.push(nextNum);
}
sequence.pop(); // remove the last element, which is greater than the limit
return sequence;
}
This function takes a limit
parameter, which is the highest number that should be included in the sequence. The function initializes the sequence with the first two Fibonacci numbers (0 and 1) and then uses a while
loop to generate the next numbers in the sequence until the last number is greater than or equal to the limit
. Finally, the function removes the last element from the sequence, since it will be greater than the limit
.
Here’s an example of how to use the function:
const sequence = generateFibonacciSequence(50);
console.log(sequence); // outputs [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Challenge 7: Prime Number Checker
In this challenge, you need to write a function that checks whether a given number is prime or not.
Here’s a potential solution:
function isPrime(num) {
if (num <= 1) {
return false; // 1 and all negative numbers are not prime
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false; // the number is divisible by i, so it's not prime
}
}
return true; // the number is not divisible by any number up to its square root, so it's prime
}
Here’s an explanation of how it works:
- The function takes a single argument,
num
, which is the number we want to check for primality. - If the number is less than or equal to 1, we know it’s not prime, so we immediately return
false
. - We then loop through all numbers from 2 up to the square root of the input number. If any of these numbers divide the input number evenly (i.e. with no remainder), we know the input number is not prime, so we return
false
. - If the loop completes without finding a factor of the input number, we know it’s prime, so we return
true
.
Here’s an example usage of this function:
console.log(isPrime(7)); // true
console.log(isPrime(12)); // false
console.log(isPrime(2)); // true
console.log(isPrime(1)); // false
Challenge 8: Capitalize Letters
In this challenge, you need to write a function that takes a string as input and capitalizes the first letter of each word in the string.
Here’s a potential solution:
function capitalizeString(str) {
let words = str.split(" "); // split the string into an array of words
for (let i = 0; i < words.length; i++) {
// loop through each word
let word = words[i];
words[i] = word.charAt(0).toUpperCase() + word.slice(1);
// capitalize the first letter of the word and append the rest of the word
}
return words.join(" "); // join the words back into a string and return it
}
You can use this function like so:
let inputString = "this is a sample string";
let capitalizedString = capitalizeString(inputString);
console.log(capitalizedString); // output: "This Is A Sample String"
In this example, the capitalizeString
function takes in a string as an argument and splits it into an array of words using the split()
method. It then loops through each word in the array and capitalizes the first letter using the toUpperCase()
method and the slice()
method to append the rest of the word. Finally, it joins the words back into a string using the join()
method and returns it.
Challenge 9: Chunky Monkey
In this challenge, you need to write a function that splits an array into smaller arrays of a specified size.
Here’s a potential solution:
function chunkArray(array, chunkSize) {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}
This function takes two arguments: the array to be chunked, and the desired size of each chunk. It then creates an empty chunks
array to store the resulting chunks.
The function then loops through the input array
, incrementing i
by chunkSize
on each iteration, and uses the slice
method to extract a chunk of the array starting at index i
and ending at index i + chunkSize
.
Each chunk is then pushed onto the chunks
array, until the entire input array has been processed.
Finally, the chunks
array is returned, containing all the smaller arrays of the specified size.
Here’s an example usage:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8];
const chunkedArray = chunkArray(myArray, 3);
console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8]]
In this example, the myArray
is split into smaller arrays of size 3
, resulting in the chunkedArray
.
Challenge 10: Max Character
In this challenge, you need to write a function that takes a string as input and returns the character that appears the most in the string.
Here’s a potential solution:
function findMostFrequentChar(str) {
// Create an object to store the frequency of each character
const charFrequency = {};
// Loop through each character in the string
for (let i = 0; i < str.length; i++) {
const char = str.charAt(i);
// If the character has already been seen, increment its count
if (char in charFrequency) {
charFrequency[char]++;
}
// Otherwise, add the character to the object with a count of 1
else {
charFrequency[char] = 1;
}
}
// Find the character with the highest frequency
let mostFrequentChar = "";
let highestFrequency = 0;
for (const char in charFrequency) {
if (charFrequency[char] > highestFrequency) {
mostFrequentChar = char;
highestFrequency = charFrequency[char];
}
}
return mostFrequentChar;
}
The function first creates an empty object called charFrequency
to store the frequency of each character in the string. Then, it loops through each character in the input string using a for
loop. For each character, the function checks if it has already been seen by checking if it exists as a key in the charFrequency
object. If the character has already been seen, the function increments its count in the object. If the character has not been seen, it is added to the object with a count of 1.
After the loop finishes, the function then iterates through the charFrequency
object to find the character with the highest frequency count. It initializes two variables, mostFrequentChar
and highestFrequency
, to keep track of the character with the highest frequency and its frequency count, respectively. The loop checks each character in the charFrequency
object and updates the mostFrequentChar
and highestFrequency
variables if a character is found with a higher frequency count than the current highest frequency count.
Finally, the function returns the character with the highest frequency count as the result.
Here’s how you could use this function:
const inputString = "hello world";
const mostFrequentChar = findMostFrequentChar(inputString);
console.log(`The most frequent character in "${inputString}" is "${mostFrequentChar}"`);