Mastering JavaScript: 10 Essential Coding Exercises

JavaScript is a powerful and versatile language essential for modern web development. Here are 10 essential coding exercises designed to enhance your JavaScript skills. Each exercise includes complete code and explanations to help you understand the concepts and improve your coding abilities.

Exercise 1: Reversing a String

Objective: Write a function to reverse a string.

Code:

function reverseString(str) {
return str.split('').reverse().join('');
}

// Example usage
console.log(reverseString('hello')); // Output: 'olleh'

Explanation: The reverseString function splits the string into an array of characters, reverses the array, and joins the characters back into a string.

Exercise 2: Checking for Palindromes

Objective: Write a function to check if a string is a palindrome.

Code:

function isPalindrome(str) {
const cleaned = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleaned === cleaned.split('').reverse().join('');
}

// Example usage
console.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: true

Explanation: The isPalindrome function removes non-alphanumeric characters, converts the string to lowercase, and checks if it reads the same forward and backward.

Exercise 3: Finding the Largest Number in an Array

Objective: Write a function to find the largest number in an array.

Code:

function findLargestNumber(arr) {
return Math.max(...arr);
}

// Example usage
console.log(findLargestNumber([1, 2, 3, 4, 5])); // Output: 5

Explanation: The findLargestNumber function uses the spread operator to pass the array elements as individual arguments to the Math.max function.

Exercise 4: Flattening a Nested Array

Objective: Write a function to flatten a nested array.

Code:

function flattenArray(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}

// Example usage
console.log(flattenArray([1, [2, [3, 4], 5], 6])); // Output: [1, 2, 3, 4, 5, 6]

Explanation: The flattenArray function uses recursion and the reduce method to flatten nested arrays.

Exercise 5: Removing Duplicates from an Array

Objective: Write a function to remove duplicates from an array.

Code:

function removeDuplicates(arr) {
return [...new Set(arr)];
}

// Example usage
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

Explanation: The removeDuplicates function converts the array to a Set to remove duplicates and then converts it back to an array.

Exercise 6: Chunking an Array

Objective: Write a function to split an array into chunks of a specified size.

Code:

function chunkArray(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}

// Example usage
console.log(chunkArray([1, 2, 3, 4, 5, 6], 2)); // Output: [[1, 2], [3, 4], [5, 6]]

Explanation: The chunkArray function uses a for loop to slice the array into chunks of the specified size.

Exercise 7: Finding the Intersection of Two Arrays

Objective: Write a function to find the intersection of two arrays.

Code:

function arrayIntersection(arr1, arr2) {
return arr1.filter(value => arr2.includes(value));
}

// Example usage
console.log(arrayIntersection([1, 2, 3], [2, 3, 4])); // Output: [2, 3]

Explanation: The arrayIntersection function uses the filter method to find elements that are present in both arrays.

Exercise 8: Calculating Factorials

Objective: Write a function to calculate the factorial of a number.

Code:

function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}

// Example usage
console.log(factorial(5)); // Output: 120

Explanation: The factorial function uses recursion to calculate the factorial of a number.

Exercise 9: Generating Fibonacci Sequence

Objective: Write a function to generate the Fibonacci sequence up to a specified number of elements.

Code:

function fibonacci(n) {
const sequence = [0, 1];
for (let i = 2; i < n; i++) {
sequence.push(sequence[i - 1] + sequence[i - 2]);
}
return sequence;
}

// Example usage
console.log(fibonacci(10)); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation: The fibonacci function generates the Fibonacci sequence up to the specified number of elements using a for loop.

Exercise 10: Implementing a Binary Search

Objective: Write a function to perform a binary search on a sorted array.

Code:

function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return -1;
}

// Example usage
console.log(binarySearch([1, 2, 3, 4, 5], 3)); // Output: 2

Explanation: The binarySearch function performs a binary search on a sorted array by repeatedly dividing the search interval in half.