Quick answer: Good JavaScript practice starts with strings, loops and conditions, then moves to arrays, objects, closures and promises. The 15 problems here include palindromes, FizzBuzz, word counts, removing duplicates, grouping, chunking, two-sum, balanced brackets, debounce and a retry function. Try each for 15 minutes before you read the solution, then rewrite it from memory the next day.
These JavaScript fundamentals practice problems go from warm-up loops to the small async tasks you meet at work. There are fifteen, in three levels. Each one has a task, a hint, a working solution and a "now change it" step.
You need only the basics: variables, functions, arrays and objects. If those are new, read the JavaScript fundamentals tutorial first.
How to use these JavaScript fundamentals exercises
- Write one input and its expected output on paper.
- Try for 15 minutes before you read the hint.
- Run your code with a normal value, an empty value and an odd value.
- Compare it with the solution. Yours can be different and still be right.
- Do the "now change it" step without copying.
Pro tip: Keep a notebook with three columns: problem, where I got stuck, and the idea that solved it. Revise the middle column before interviews.
JavaScript fundamentals practice problems, Level 1: Strings, numbers and loops
1. Check a palindrome
Task: Return true if a phrase reads the same both ways. Ignore capitals, spaces and symbols.
Hint: Clean the text first, then compare it with its reverse.
function isPalindrome(text) {
const clean = text.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === [...clean].reverse().join("");
}
console.log(isPalindrome("Never odd or even")); // true
console.log(isPalindrome("JavaScript")); // false
Now change it: Use two indexes, one from each end, and no reverse.
2. Print FizzBuzz
Task: Return the values from 1 to n. Use "Fizz" for multiples of 3, "Buzz" for 5 and "FizzBuzz" for both.
Hint: Which test must come first?
function fizzBuzz(n) {
const out = [];
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) out.push("FizzBuzz");
else if (i % 3 === 0) out.push("Fizz");
else if (i % 5 === 0) out.push("Buzz");
else out.push(i);
}
return out;
}
console.log(fizzBuzz(15).slice(8)); // [ 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz' ]
The test for 15 comes first. Otherwise 15 would match "Fizz" and stop there.
Now change it: Take the two numbers and two words as parameters.
3. Capitalise each word
Task: Turn "learn javascript fast" into "Learn Javascript Fast", with single spaces.
Hint: Split on one or more spaces.
function titleCase(text) {
return text
.trim()
.split(/\s+/)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
}
console.log(titleCase(" learn javascript fast ")); // Learn Javascript Fast
charAt(0) is safe for an empty string. w[0] would be undefined and cause an error.
Now change it: Make the result camelCase.
4. Test for a prime number
Task: Return true if a whole number is prime.
Hint: You can stop at the square root.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
console.log([1, 2, 9, 29].map((n) => isPrime(n))); // [ false, true, false, true ]
If a number has a factor above its square root, the matching factor is below it. That is why the loop can stop early.
Now change it: List all primes up to 50.
5. Find the missing number
Task: An array holds every number from 1 to n except one. Find it.
Hint: Compare two totals.
function missingNumber(list) {
const n = list.length + 1;
const expected = (n * (n + 1)) / 2;
return expected - list.reduce((a, b) => a + b, 0);
}
console.log(missingNumber([4, 1, 5, 2])); // 3
One pass is enough, and no sorting is needed.
Now change it: Solve it with a Set.
Level 2: Arrays and objects
6. Find the second largest value
Task: Return the second largest different number, or null if there is none.
Hint: Track two values as you loop.
function secondLargest(list) {
let first = -Infinity;
let second = -Infinity;
for (const n of list) {
if (n > first) {
second = first;
first = n;
} else if (n < first && n > second) {
second = n;
}
}
return second === -Infinity ? null : second;
}
console.log(secondLargest([8, 15, 15, 3])); // 8
console.log(secondLargest([7, 7])); // null
The check n < first stops a repeated 15 from becoming second.
Now change it: Return the two smallest values.
7. Count words
Task: Return an object with the count of each word.
Hint: Use the word as a key.
function countWords(text) {
const counts = {};
for (const word of text.toLowerCase().match(/[a-z]+/g) ?? []) {
counts[word] = (Object.hasOwn(counts, word) ? counts[word] : 0) + 1;
}
return counts;
}
console.log(countWords("Code, test, code.")); // { code: 2, test: 1 }
match returns null when nothing is found, so ?? [] keeps the loop safe. Object.hasOwn protects words such as "constructor", which a plain object already inherits.
Now change it: Return only the most common word.
8. Remove duplicate objects
Task: Keep the first object for each id.
Hint: Remember the ids you have seen.
function uniqueById(items) {
const seen = new Set();
return items.filter((item) => {
if (seen.has(item.id)) return false;
seen.add(item.id);
return true;
});
}
const rows = [{ id: 1 }, { id: 2 }, { id: 1 }];
console.log(uniqueById(rows)); // [ { id: 1 }, { id: 2 } ]
A direct new Set(rows) would not work. Two objects with the same data are still two separate objects.
Now change it: Keep the last object for each id.
9. Group students by branch
Task: Return an object with branches as keys and arrays of names as values.
Hint: Create the array the first time you see a branch.
function groupByBranch(list) {
return list.reduce((groups, s) => {
(groups[s.branch] ??= []).push(s.name);
return groups;
}, {});
}
const students = [
{ name: "Sai", branch: "CSE" },
{ name: "Meena", branch: "ECE" },
{ name: "Arif", branch: "CSE" },
];
console.log(groupByBranch(students)); // { CSE: [ 'Sai', 'Arif' ], ECE: [ 'Meena' ] }
??= assigns a value only when the left side is null or undefined.
Now change it: Count students in each branch.
10. Split an array into chunks
Task: Split a list into parts of a given size. The last part may be smaller.
Hint: Increase the loop index by size.
function chunk(list, size) {
if (!Number.isInteger(size) || size < 1) throw new RangeError("Bad size");
const out = [];
for (let i = 0; i < list.length; i += size) {
out.push(list.slice(i, i + size));
}
return out;
}
console.log(chunk([1, 2, 3, 4, 5], 2)); // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
This is the idea behind showing results in pages. Without the size check, a size of 0 would loop forever.
Now change it: Return only page number 2.
Level 3: Interview-style problems
11. Two-sum
Task: Return the indexes of two numbers that add up to a target, or null.
Hint: For each number, which partner do you need?
function twoSum(list, target) {
const seen = new Map();
for (let i = 0; i < list.length; i++) {
const need = target - list[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(list[i], i);
}
return null;
}
console.log(twoSum([4, 9, 2, 11], 13)); // [ 0, 1 ]
console.log(twoSum([1, 2], 10)); // null
The Map lets you find a partner without a second loop, so average time is O(n).
Interview note: Give the two-loop answer first and say it is O(n²). Then improve it. Interviewers like to hear how you get from one to the other.
12. Check balanced brackets
Task: Decide whether every (, [ and { is closed in the right order.
Hint: The last bracket opened must be the first one closed. Use a stack.
function isBalanced(text) {
const pairs = new Map([[")", "("], ["]", "["], ["}", "{"]]);
const stack = [];
for (const ch of text) {
if ("([{".includes(ch)) stack.push(ch);
else if (pairs.has(ch) && stack.pop() !== pairs.get(ch)) return false;
}
return stack.length === 0;
}
console.log(isBalanced("{[()]}")); // true
console.log(isBalanced("(]")); // false
console.log(isBalanced("((")); // false
The final length check catches brackets that were opened and never closed.
Now change it: Return the position of the first wrong bracket.
13. Flatten a nested array
Task: Flatten any depth without flat.
Hint: If an item is an array, call the same function on it.
function flatten(list) {
return list.reduce(
(out, x) => out.concat(Array.isArray(x) ? flatten(x) : [x]),
[]
);
}
console.log(flatten([1, [2, [3, [4]]]])); // [ 1, 2, 3, 4 ]
A function that calls itself is recursive. Here it stops when it finds no more arrays inside.
Now change it: Solve it with a stack and no recursion.
14. Write debounce
Task: Return a function that runs only after calls have stopped for ms milliseconds. Search boxes use this.
Hint: Keep the timer in a closure and clear it on every call.
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const search = debounce((text) => console.log("Search:", text), 30);
search("j");
search("ja");
search("java");
Search: java
Each call cancels the one before it, so only the last survives. Revise the idea with closure questions.
Now change it: Add a cancel method to the returned function.
15. Retry a failing task
Task: Run an async function up to times attempts. Throw the last error if all fail.
Hint: Put try...catch inside a loop.
async function retry(task, times) {
let lastError = new Error("No attempts made");
for (let i = 1; i <= times; i++) {
try {
return await task();
} catch (error) {
lastError = error;
console.log(`Attempt ${i} failed`);
}
}
throw lastError;
}
let calls = 0;
const flaky = async () => {
if (++calls < 3) throw new Error("Network");
return "OK";
};
retry(flaky, 5).then((result) => console.log(result));
Attempt 1 failed
Attempt 2 failed
OK
Common mistake: Writing
return task()withoutawaithere. The promise would leave thetryblock before it fails, socatchwould never see the error.
Now change it: Wait 100 ms between attempts.
What to do after this JavaScript fundamentals coding practice
Use this plan to turn JavaScript fundamentals problems and solutions into lasting skill:
| Day | Task |
|---|---|
| 1 to 5 | Three problems a day, with notes |
| 6 | Redo every problem you got wrong |
| 7 | Solve five random ones in 60 minutes |
When a solution fails, compare it with these common JavaScript mistakes. Then practise explaining answers with our interview questions.
After your JavaScript fundamentals coding practice, the full stack developer course guide explains how these skills lead to React and Node.js. You can study them with us in the Full Stack Web Development programme.
Frequently asked questions
How many JavaScript problems should a beginner solve?
Around 50 small problems give you a good base before you start a framework. Quality matters more than the number. Solve a problem, change its rules and solve it again without looking at your first answer.
Should I use built-in methods in coding rounds?
Ask the interviewer. If they are allowed, methods such as map, filter and Set make your code short and clear. Practise a loop version too, because some interviewers ask you not to use built-ins.
What should I do when I cannot solve a JavaScript problem?
Write one example by hand and note each step you take. Read the hint and try again for ten minutes. If you are still stuck, study the solution, close it and write it again the next day.
Where can I run these JavaScript exercises?
Save each solution in a file and run it with Node.js, or paste it into the console of a browser. Every solution on this page was run with Node.js, and the output appears in comments or below the code.
Are these problems enough for a fresher coding round?
They cover common warm-up patterns, but they are a starting point. Add more string, array and hashing problems, and practise explaining the time complexity of your solution in simple words.
Want a trainer to review your solutions? Book a free demo class and see how we teach in batches of up to 27. For a longer plan, follow the full stack developer roadmap.
