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.
It prints
What the tests check
divide(10, 2)gives5- 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
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.