Throw an error when dividing by zero

“Safe division”, a Green belt challenge from the CurlyScript Dojo. It uses what Summer School: Debugging: Becoming a Bug Detective teaches, and 2 tests check your answer.

The challenge

Write divide(a, b) that returns a / b, but throws an Error with the message "Cannot divide by zero" when b is 0.

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • divide(10, 2) gives 5
  • Dividing by zero throws "Cannot divide by zero": (() => { try { divide(1, 0); return "no error"; } catch (e) { return e.message; } })() gives "Cannot divide by zero"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

if (b === 0) throw new Error("Cannot divide by zero");

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

Learn what you need

This exercise uses what Summer School: Debugging: Becoming a Bug Detective teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning