# 10 JavaScript coding challenges

January 12, 2023

Preparing for a JavaScript interview can be a daunting task, as the language is versatile and has a wide range of applications. One of the best ways to prepare is to practice solving coding challenges. In this article, we’ll provide a list of coding challenges, ordered from easiest to hardest, along with solutions and explanations.

## 1) Reverse a string:

``````function reverseString(str) {
return str.split("").reverse().join("")
}
console.log(reverseString("hello")) // should output 'olleh'``````

This is a basic problem that requires you to reverse a string. The solution makes use of JavaScript’s built-in `split()`, `reverse()`, and `join()` methods to accomplish this. The split() method is used to convert the string into an array of characters, the `reverse()` method is used to reverse the order of the characters in the array, and the `join()` method is used to convert the array back into a string.

## 2) Find the largest number in an array:

``````function findLargestNum(arr) {
return Math.max(...arr)
}
console.log(findLargestNum([1, 2, 3, 4, 5])) // should output 5``````

This is a simple problem that requires you to find the largest number in an array. The solution makes use of the `Math.max()` function, which returns the largest number in a list of arguments. In this case, the spread operator (…) is used to pass the entire array as a list of arguments to the `Math.max()` function.

## 2) Check if a number is prime:

``````function isPrime(num) {
for (let i = 2; i < num; i++) if (num % i === 0) return false
return num !== 1
}
console.log(isPrime(7)) // should output true``````

This problem requires you to check if a number is prime or not. A prime number is a number greater than 1 which is divisible by only 1 and itself. The solution uses a for loop to iterate through all numbers between 2 and the input number, checking if the input number is divisible by any of them. If it is divisible, it means it is not prime.

## 4) Find the common elements in two arrays:

``````function commonElements(arr1, arr2) {
return arr1.filter(val => arr2.includes(val))
}
console.log(commonElements([1, 2, 3], [2, 3, 4])) // should output [2, 3]``````

This problem requires you to find the common elements in two arrays. The solution uses the `filter()` method to filter through the first array, checking each element to see if it’s included in the second array using the `includes()` method. The common elements are returned in a new array.

## 5) Implement a function to check if a given string is a palindrome:

``````function isPalindrome(str) {
return str === str.split("").reverse().join("")
}
console.log(isPalindrome("racecar")) // should output true``````

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. The solution uses the same method used in reversing a string, but this time we use it to compare the original string with its reverse.

## 6) Implement a function to implement merge sort:

``````function mergeSort(arr) {
if (arr.length < 2) {
return arr
}
const middle = Math.floor(arr.length / 2)
const left = arr.slice(0, middle)
const right = arr.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}

function merge(left, right) {
let result = []
let leftIndex = 0
let rightIndex = 0
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex])
leftIndex++
} else {
result.push(right[rightIndex])
rightIndex++
}
}
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex))
}
console.log(mergeSort([4, 3, 2, 1])) // should output [1,2,3,4]``````

This challenge is a little bit more advanced, it requires you to implement the merge sort algorithm which is a sorting algorithm that follows the divide and conquer approach. The merge sort algorithm repeatedly divides the array in half and then merges the sorted halves back together.

## 7) Implement a breadth-first search algorithm:

``````function breadthFirstSearch(root, target) {
let queue = [root]
while (queue.length) {
let node = queue.shift()
if (node.value === target) {
return node
}
for (let i = 0; i < node.children.length; i++) {
queue.push(node.children[i])
}
}
return null
}``````

This challenge requires you to implement a breadth-first search algorithm, which is a method for traversing and searching a tree or graph data structure. The algorithm starts at the root node and explores the neighbor nodes first, before moving on to the next level neighbors. It uses a queue data structure to keep track of the nodes to be explored next.

## 8) Implement a function to check if a given number is a fibonacci number:

``````function isFibonacci(num) {
let a = 0,
b = 1,
c = 0
while (c < num) {
c = a + b
if (c === num) {
return true
}
a = b
b = c
}
return false
}
console.log(isFibonacci(8)) // should output true``````

A fibonacci number is a number that is part of the fibonacci sequence, in which each number is the sum of the two preceding ones. This problem requires you to check if a given number is a fibonacci number or not. The solution uses a while loop to generate fibonacci numbers and compare them to the input number.

## 9) Implement a function to find the missing element in an array:

``````function findMissing(arr) {
let sum = 0
let n = arr.length + 1
let expectedSum = (n * (n + 1)) / 2
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
return expectedSum - sum
}
console.log(findMissing([1, 2, 4, 6, 3, 7, 8])) // should output 5``````

This problem requires you to find the missing element in an array. The solution first calculates the expected sum of an array of n elements, then it calculates the actual sum of the input array by adding its elements. The missing element is then calculated by subtracting the actual sum from the expected sum.

## 10) Implement a function to implement a depth-first search algorithm:

``````function depthFirstSearch(root, target) {
if (root.value === target) {
return root
}
for (let i = 0; i < root.children.length; i++) {
let result = depthFirstSearch(root.children[i], target)
if (result !== null) {
return result
}
}
return null
}``````

This problem requires you to implement a depth-first search algorithm, which is a method for traversing and searching a tree or graph data structure. The algorithm starts at the root node and explores as far as possible along each branch before backtracking. It uses a recursive function to traverse the tree and check each node’s value against the target value.

Remember that practice and persistence are key to mastering any skill, and that’s also true for coding interviews. By practicing coding challenges, you can gain a better understanding of the language and gain the confidence you need to ace your interview. With a bit of hard work and dedication, you can become a JavaScript expert and land your dream job. Good luck! Chafik Gharbi Full-stack web and mobile app developer with JavaScript.