TExcelTAD
Home › JavaScript › JavaScript Exercises

JavaScript Exercises

Time to practise! Each exercise below has a starter playground: the tests at the bottom are already written, and your job is to complete the function marked TODO until the output matches the expected output. Try each one yourself before opening the solution — getting stuck for a few minutes is how learning happens.

Tip: Run the starter first. It prints the wrong answers (often undefined), which shows you what the tests expect. Change the code, press Ctrl+Enter, repeat.

Exercise 1: Temperature converter

Topics: functions, arithmetic, toFixed

Write toFahrenheit(celsius) that converts Celsius to Fahrenheit (F = C × 9/5 + 32) and returns a string with one decimal place followed by °F.

js · try it yourself
function toFahrenheit(celsius) {
  // TODO: convert and format
}

console.log(toFahrenheit(0));
console.log(toFahrenheit(100));
console.log(toFahrenheit(-40));
console.log(toFahrenheit(36.6));

Expected output:

text
32.0°F
212.0°F
-40.0°F
97.9°F
Show solution
js
function toFahrenheit(celsius) {
  const f = (celsius * 9) / 5 + 32;
  return `${f.toFixed(1)}°F`;
}

console.log(toFahrenheit(0));
console.log(toFahrenheit(100));
console.log(toFahrenheit(-40));
console.log(toFahrenheit(36.6));

Exercise 2: FizzBuzz

Topics: loops, %, if…else

Return an array with the numbers 1 to n, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".

js · try it yourself
function fizzBuzz(n) {
  const result = [];
  // TODO: fill the array
  return result;
}

console.log(fizzBuzz(15).join(" "));

Expected output:

text
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Show solution
js
function fizzBuzz(n) {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push("FizzBuzz");
    else if (i % 3 === 0) result.push("Fizz");
    else if (i % 5 === 0) result.push("Buzz");
    else result.push(i);
  }
  return result;
}

console.log(fizzBuzz(15).join(" "));

Checking % 15 first matters: a number divisible by 15 is also divisible by 3, so the order of the conditions decides the result.

Exercise 3: Palindromes

Topics: strings, string methods, regular expressions

A palindrome reads the same forwards and backwards. Write isPalindrome(text) that ignores case, spaces and punctuation.

js · try it yourself
function isPalindrome(text) {
  // TODO: normalise the text, then compare it with its reverse
}

console.log(isPalindrome("racecar"));
console.log(isPalindrome("A man, a plan, a canal: Panama!"));
console.log(isPalindrome("JavaScript"));
console.log(isPalindrome("Was it a car or a cat I saw?"));

Expected output:

text
true
true
false
true
Show solution
js
function isPalindrome(text) {
  const clean = text.toLowerCase().replace(/[^a-z0-9]/g, "");
  const reversed = [...clean].reverse().join("");
  return clean === reversed;
}

console.log(isPalindrome("racecar"));
console.log(isPalindrome("A man, a plan, a canal: Panama!"));
console.log(isPalindrome("JavaScript"));
console.log(isPalindrome("Was it a car or a cat I saw?"));

Exercise 4: Grade statistics

Topics: arrays, reduce, Math.max, filter

Given an array of scores, return an object with the average (rounded to one decimal), the highest score, and how many scores passed (50 or more).

js · try it yourself
function stats(scores) {
  // TODO: return { average, highest, passed }
}

console.log(stats([72, 45, 90, 63, 38, 81]));
console.log(stats([100]));

Expected output:

text
{ average: 64.8, highest: 90, passed: 4 }
{ average: 100, highest: 100, passed: 1 }
Show solution
js
function stats(scores) {
  const total = scores.reduce((sum, s) => sum + s, 0);
  return {
    average: Math.round((total / scores.length) * 10) / 10,
    highest: Math.max(...scores),
    passed: scores.filter((s) => s >= 50).length,
  };
}

console.log(stats([72, 45, 90, 63, 38, 81]));
console.log(stats([100]));

Exercise 5: Word frequency

Topics: strings, Map or objects, sorting

Write topWords(text, n) that returns the n most frequent words (lowercase) as "word: count" strings, most frequent first. Words with the same count keep their first-seen order.

js · try it yourself
function topWords(text, n) {
  // TODO: count words, sort by count, take n
}

const text = "The quick fox and the lazy dog. The dog sleeps, the fox runs!";
console.log(topWords(text, 3));

Expected output:

text
[ 'the: 4', 'fox: 2', 'dog: 2' ]
Show solution
js
function topWords(text, n) {
  const words = text.toLowerCase().match(/[a-z']+/g) ?? [];
  const counts = new Map();
  for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
  return [...counts]
    .sort((a, b) => b[1] - a[1])            // sort is stable: ties keep insertion order
    .slice(0, n)
    .map(([word, count]) => `${word}: ${count}`);
}

const text = "The quick fox and the lazy dog. The dog sleeps, the fox runs!";
console.log(topWords(text, 3));

Exercise 6: Shopping cart class

Topics: classes, private fields, getters, array methods

Complete the Cart class: add(name, price, qty = 1) adds an item (or increases the quantity if it's already in the cart) and returns this for chaining; remove(name) deletes an item; the getter total returns the sum rounded to 2 decimals; count returns the total number of units.

js · try it yourself
class Cart {
  #items = new Map();   // name -> { price, qty }

  add(name, price, qty = 1) {
    // TODO
    return this;
  }

  remove(name) {
    // TODO
  }

  get total() {
    // TODO
  }

  get count() {
    // TODO
  }
}

const cart = new Cart();
cart.add("apple", 0.4, 5).add("bread", 2.3).add("apple", 0.4, 2);
console.log(cart.count, cart.total);
cart.remove("bread");
console.log(cart.count, cart.total);

Expected output:

text
8 5.1
7 2.8
Show solution
js
class Cart {
  #items = new Map();

  add(name, price, qty = 1) {
    const existing = this.#items.get(name);
    if (existing) existing.qty += qty;
    else this.#items.set(name, { price, qty });
    return this;
  }

  remove(name) {
    this.#items.delete(name);
  }

  get total() {
    let sum = 0;
    for (const { price, qty } of this.#items.values()) sum += price * qty;
    return Math.round(sum * 100) / 100;
  }

  get count() {
    let units = 0;
    for (const { qty } of this.#items.values()) units += qty;
    return units;
  }
}

const cart = new Cart();
cart.add("apple", 0.4, 5).add("bread", 2.3).add("apple", 0.4, 2);
console.log(cart.count, cart.total);
cart.remove("bread");
console.log(cart.count, cart.total);

Rounding in total hides floating-point noise such as 2.8000000000000003.

Exercise 7: Group by

Topics: objects, reduce, callbacks

Write groupBy(array, keyFn) that returns an object whose keys are the results of keyFn(item) and whose values are arrays of the matching items, in their original order.

js · try it yourself
function groupBy(array, keyFn) {
  // TODO
}

const people = [
  { name: "Ana", city: "Lisbon" },
  { name: "Ben", city: "Berlin" },
  { name: "Cleo", city: "Lisbon" },
];
console.log(groupBy(people, (p) => p.city));
console.log(groupBy([1, 2, 3, 4, 5, 6], (n) => (n % 2 === 0 ? "even" : "odd")));

Expected output:

text
{
  Lisbon: [ { name: 'Ana', city: 'Lisbon' }, { name: 'Cleo', city: 'Lisbon' } ],
  Berlin: [ { name: 'Ben', city: 'Berlin' } ]
}
{ odd: [ 1, 3, 5 ], even: [ 2, 4, 6 ] }
Show solution
js
function groupBy(array, keyFn) {
  return array.reduce((groups, item) => {
    const key = keyFn(item);
    (groups[key] ??= []).push(item);
    return groups;
  }, {});
}

const people = [
  { name: "Ana", city: "Lisbon" },
  { name: "Ben", city: "Berlin" },
  { name: "Cleo", city: "Lisbon" },
];
console.log(groupBy(people, (p) => p.city));
console.log(groupBy([1, 2, 3, 4, 5, 6], (n) => (n % 2 === 0 ? "even" : "odd")));

Modern engines also provide this built in as Object.groupBy(array, keyFn).

Exercise 8: Retry with promises

Topics: async/await, error handling, loops

flakyTask() fails twice and then succeeds. Write retry(task, attempts) that calls task() up to attempts times, logging each failure, and returns the first successful result. If every attempt fails, throw an error with the message "All N attempts failed".

js · try it yourself
let calls = 0;
async function flakyTask() {
  calls++;
  if (calls < 3) throw new Error(`failure #${calls}`);
  return "success on call " + calls;
}

async function retry(task, attempts) {
  // TODO
}

console.log(await retry(flakyTask, 5));

calls = -10;   // now it will keep failing
try {
  await retry(flakyTask, 2);
} catch (err) {
  console.log(err.message);
}

Expected output:

text
attempt 1 failed: failure #1
attempt 2 failed: failure #2
success on call 3
attempt 1 failed: failure #-9
attempt 2 failed: failure #-8
All 2 attempts failed
Show solution
js
let calls = 0;
async function flakyTask() {
  calls++;
  if (calls < 3) throw new Error(`failure #${calls}`);
  return "success on call " + calls;
}

async function retry(task, attempts) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return await task();     // `return await` so the catch below sees rejections
    } catch (err) {
      console.log(`attempt ${i} failed: ${err.message}`);
    }
  }
  throw new Error(`All ${attempts} attempts failed`);
}

console.log(await retry(flakyTask, 5));

calls = -10;
try {
  await retry(flakyTask, 2);
} catch (err) {
  console.log(err.message);
}

Test yourself

In FizzBuzz, why must the % 15 check come first?

  1. It is faster
  2. Multiples of 15 are also multiples of 3 and 5, so later checks would never be reached
  3. JavaScript evaluates if statements from the bottom up
  4. It doesn't matter

Which expression reverses the string s?

  1. s.reverse()
  2. [...s].reverse().join("")
  3. s.split().reverse()
  4. s.sort().reverse()

Why does the retry solution use return await task() inside try?

  1. It's required syntax
  2. Without await, a rejected promise would be returned instead of caught by the catch block
  3. It makes the task run in parallel
  4. It converts errors to strings