10 Beginner-Friendly JavaScript Problems Solved: Step-by-Step Code Examples
10 Beginner-Friendly JavaScript Problems Solved: Step-by-Step Code Examples
Starting your journey with JavaScript can feel overwhelming, but the best way to learn is by writing code. Working through small, concrete problems helps you build confidence and understand core concepts like loops, conditionals, arrays, and strings. In this post, we will walk through ten beginner-friendly JavaScript problems. For each problem, you will see a clear explanation of the logic and a complete code example that you can run and modify. By the end, you will have a solid foundation for tackling more complex challenges.
Problem 1: Reverse a String
Reversing a string is a classic exercise that demonstrates how to work with strings and arrays. The idea is to take an input string and return a new string with characters in reverse order. A common approach is to convert the string to an array, reverse the array, and join it back into a string.
function reverseString(str) {
// Step 1: split the string into an array of characters
let arr = str.split('');
// Step 2: reverse the array
let reversedArr = arr.reverse();
// Step 3: join the array back into a string
let reversedStr = reversedArr.join('');
return reversedStr;
}
console.log(reverseString('hello')); // "olleh"You can also chain the methods for a more concise version:
const reverseString = (str) => str.split('').reverse().join('');Problem 2: Check if a Number is Even or Odd
Determining whether a number is even or odd is a fundamental conditional logic problem. The modulus operator % returns the remainder after division. If a number divided by 2 has no remainder, it is even; otherwise, it is odd.
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(7)); // falseYou can also write a version that returns a string:
function checkEvenOrOdd(num) {
if (num % 2 === 0) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}Problem 3: Find the Maximum Number in an Array
Given an array of numbers, find the largest value. You can solve this by iterating through the array and keeping track of the maximum seen so far. Alternatively, JavaScript’s Math.max combined with the spread operator offers a simpler solution.
function findMax(numbers) {
// If array is empty, return undefined
if (numbers.length === 0) return undefined;
let max = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
console.log(findMax([3, 7, 2, 9, 4])); // 9Using Math.max:
const findMax = (numbers) => Math.max(...numbers);Problem 4: Count Vowels in a String
Count how many vowels (a, e, i, o, u) appear in a given string. You can use a loop to check each character against a Set of vowels, or use a regular expression.
function countVowels(str) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
const lowerStr = str.toLowerCase();
for (let char of lowerStr) {
if (vowels.includes(char)) {
count++;
}
}
return count;
}
console.log(countVowels('Hello World')); // 3Using match with a regex:
const countVowels = (str) => (str.match(/[aeiou]/gi) || []).length;Problem 5: FizzBuzz
FizzBuzz is a famous interview problem. Print numbers from 1 to n. For multiples of 3 print "Fizz" instead of the number, for multiples of 5 print "Buzz", and for multiples of both 3 and 5 print "FizzBuzz".
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);
}
}
}
fizzBuzz(15);Output for 15:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzProblem 6: Check if a String is a Palindrome
A palindrome reads the same forwards and backwards (ignoring case and punctuation). The easiest way is to reverse the string and compare it to the original after normalizing.
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
const cleanStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
const reversed = cleanStr.split('').reverse().join('');
return cleanStr === reversed;
}
console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('Hello')); // false
console.log(isPalindrome('A man, a plan, a canal, Panama')); // trueProblem 7: Sum of All Numbers in an Array
Add every element in a numeric array. You can use a simple loop or the reduce method for a functional approach.
function sumArray(numbers) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
console.log(sumArray([1, 2, 3, 4, 5])); // 15Using reduce:
const sumArray = (numbers) => numbers.reduce((acc, curr) => acc + curr, 0);Problem 8: Remove Duplicates from an Array
Given an array with duplicate values, return a new array containing only unique elements. The Set object in JavaScript provides a straightforward solution.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]If you want to avoid Set for learning purposes, you can use a loop and an accumulator:
function removeDuplicatesManual(arr) {
const unique = [];
for (let item of arr) {
if (!unique.includes(item)) {
unique.push(item);
}
}
return unique;
}Problem 9: Find the Factorial of a Number
The factorial of a non-negative integer n (denoted as n!) is the product of all positive integers less than or equal to n. By convention, 0! = 1. You can implement it recursively or with a loop.
function factorial(n) {
if (n < 0) return undefined; // factorial undefined for negative numbers
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // 120 (1 * 2 * 3 * 4 * 5)Recursive version:
const factorial = (n) => {
if (n < 0) return undefined;
if (n === 0) return 1;
return n * factorial(n - 1);
};Problem 10: Generate a Random Number Between Two Values
Often you need a random integer between a minimum and maximum (inclusive). Math.random() returns a decimal between 0 and 1. Scale and shift it to your range.
function randomBetween(min, max) {
// min and max are inclusive
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomBetween(1, 10)); // random integer from 1 to 10Explanation: Math.random() gives [0, 1). Multiply by (max - min + 1) to get [0, range). Add min and floor it to get an integer from min to max inclusive.
These ten problems cover essential JavaScript patterns: string manipulation, array iteration, conditionals, and recursion. Practice writing each solution from scratch, then try combining concepts or adding your own twists. Consistent practice with small problems is the fastest way to become a fluent JavaScript developer.
Comments
Related posts
Setting Up Better Auth with MongoDB in Your Next.js Application
Learn how to seamlessly integrate Better Auth with MongoDB in your Next.js app for a secure, serverless-ready authentication layer—covering everything from setup to route protection in just a few steps.
Jun 17, 2026 · 6 min read
Persist React State Like a Pro: Building a Reusable useLocalState Hook
React's state resets on page refresh, but by combining localStorage with a custom `useLocalState` hook, you can create persistent state that survives browser reloads and sessions while maintaining the familiar `useState` interface.
Jun 13, 2026 · 3 min read
Deploy Like a Developer: Zero-Config Deployment from Your Terminal with Vercel CLI
After perfecting your project, a fast zero-config way to deploy it online is using Vercel: sign up, install the Vercel CLI globally, authenticate via `vercel login`, then deploy to production with `vercel --prod`.
Jun 13, 2026 · 3 min read