JavaScript debugging exercises
JavaScript is forgiving in the worst way: read past the end of an array and you get undefined, add a number to a string and you get text, forget an await and you get a Promise. The program keeps running and the bug surfaces somewhere else. These exercises train you to trace that kind of failure back to its cause.
Each one is a short function with one bug, the symptom it produces, and tests that pass only once it is fixed. They run in a sandboxed worker in your browser, from array bounds and missing returns up to closures and async race conditions.
Practise by topic
How to debug a JavaScript function
- Find where the wrong value first appears. undefined and NaN travel: log the inputs and each intermediate value until you reach the first one that is already wrong.
- Check the types, not just the values. typeof and Array.isArray tell you whether "5" is a string, and whether that list is really an array.
- Read the error message literally. "Cannot read properties of undefined (reading 'name')" means the thing before .name was undefined, not name itself.
- For async code, check what is actually awaited. A function that returns a Promise you never awaited finishes later than everything that depends on it.
- Rerun every test after the fix. If another case breaks, the fix was in the wrong place.
JavaScript debugging tools to practise with
console.log()
console.log({ i, total })Wrap the variables in braces and the output labels each value with its name, so you can see which one goes wrong first.
debugger
debugger;With DevTools open, the browser pauses on this line. Hover any variable to see its value, then step one line at a time.
DevTools breakpoints
Sources panel: click a line numberThe same pause without editing the code. Add a condition, such as i === 5, to stop only on the iteration that fails.
typeof and Array.isArray()
typeof total // "string"?Most JavaScript bugs are a value of the wrong type. Check the type of the value before you check the logic.
In the exercises, each check shows what your function returned and any error. To watch values change line by line, paste the code into the step-through visualizer. Use debugger and DevTools on your own pages.
The exercises
Easy
- Dashboard crashes for a user with no addressNull and undefined
- isEven says 4 is not evenLogic
- Cart total shows "01020" instead of 30Type
- First 3 items comes back with only 2Off-by-one
- First item name crashes on an empty listNull and undefined
- Free shipping not given at exactly 50Logic
- Capitalize turns "debug" into "Ddebug"Off-by-one
- getName gives back undefinedAsync and race conditions
- Doubling until past a limit never stopsInfinite loops
- Adding up [1, 2, 3] gives NaNOff-by-one
- Number sort puts 10 before 2Logic
- Adding shipping gives a list of undefinedNull and undefined
- Playlist shows undefined as the last songOff-by-one
- Validator never finds the negative numberLogic
- Counting positives crashes on the first oneType
- Highest price comes back as NaNLogic
- Word counter shows NaNNull and undefined
- Correct PIN is rejectedType
- Digit sum gives "0123" instead of 6Type
- Counting settings returns undefinedNull and undefined
- Stock check can't find the first productLogic
- Palindrome check fails on capitalised wordsLogic
- Score total skips the first roundOff-by-one
- Zero percent promo code triggers fallback discountLogic
- Filtering products by inventory drops items with zero countLogic
- Empty array evaluated in boolean condition returns trueLogic
- Sorting numbers puts 100 before 25 and alters original arrayLogic
- Accessing last element with negative index returns undefinedLogic
- Token expiry check marks future tokens as expiredType
- Math min on empty price list returns positive infinityLogic
- Parsing string numbers with array map returns NaN and binaryType
- Joining URL path parts with null leaves double slashLogic
- Empty cart tax calculation raises TypeError in reduceType
- Query string literal null value treated as valid stringType
- Removing dashes from phone number leaves trailing hyphensLogic
- Checking property with in operator matches prototype methodsLogic
- Floating point balance calculation leaves precision artifactLogic
- Array unshift returns new length instead of prepended arrayType
- Helper adding role returns array length instead of arrayType
- Clamping percentage bounds inverted returns upper limitLogic
- Null profile object crashes name lookup with TypeErrorNull and undefined
- Find index returning zero evaluated as falsy in conditionLogic
- Deleting array element leaves empty slot instead of removingLogic
- Padding invoice number with padEnd appends trailing zeroesLogic
- Array find returning zero treated as not foundLogic
- Adding toFixed result to number performs string concatenationType
- Destructuring default value skipped when property is nullNull and undefined
- Array indexOf looking up object returns negative oneLogic
- Splitting empty string returns array with length oneLogic
- String substring with negative argument treats index as zeroLogic
- Math max on empty score list returns negative infinityLogic
- Encoding query redirect URL with encodeURI leaves delimiters unescapedLogic
- Helper dropping first item returns deleted item with spliceLogic
- Array constructor with map skips uninitialized empty slotsLogic
- Iterating array with for in treats indices as string concatenationType
- Math floor on negative coordinate rounds down to lower integerLogic
- Sorting mixed case words orders capital letters before lowercaseLogic
- Single equals assignment in condition grants admin access to allLogic
- Query parameter false string converted to boolean evaluates to trueType
- Flattening nested category list leaves inner arrays unflattenedLogic
- Array shift removes first element and returns removed itemLogic
- Checking if order quantity is integer fails on string numbersType
- Empty string input coerced to zero by Number constructorType
- Checking all items in empty cart are in stock returns trueLogic
- Array pop on array with zero element returns fallback valueLogic
- Parsing number with trailing letters produces partial integerType
- Deduplicating objects in array with Set returns duplicatesLogic
- Sort comparator returning boolean never returns negative oneLogic
- Malformed token string causes JSON parse to throw SyntaxErrorType
- Shout button doesn't shoutMutation and copying
- URL slug only replaces the first spaceLogic
- Overdue warning shows for every library cardLogic
- Thank-you message prints ${name} literallyLogic
- Every review gets the Top rated badgeLogic
- Total points misses the last gameOff-by-one
Medium
- Finding the first negative number crashesScope and closure
- Last 2 items comes back with 3Off-by-one
- Score total turns into NaNNull and undefined
- Sorting puts 9 after 100Type
- Member discount crashes with ReferenceErrorScope and closure
- Vote total shows "034" instead of 7Type
- Word lengths come back as promises, not numbersAsync and race conditions
- Total shows "[object Promise]" instead of 6Async and race conditions
- 0.1 + 0.2 gives 0.30000000000000004Mutation and copying
- Flattening stops after one levelMutation and copying
- Grouping words keeps only one per groupLogic
- Cart total ignores how many of each itemLogic
- Loading 3 items returns only oneAsync and race conditions
- Doubling after a delay returns undefinedAsync and race conditions
- Names list is full of promises, not textAsync and race conditions
- Adding a fee crashes before the fee existsScope and closure
- Counting matches always gives 0Scope and closure
- Counting odd numbers freezes on an even oneInfinite loops
- Counting capitals freezes on a lowercase letterInfinite loops
- Zero counter also counts "" and falseType
- 1.5 + 2.5 comes out as 3Type
- Setting retries to 0 turns them back onNull and undefined
- Price lookup crashes for an unknown itemNull and undefined
- Joining words leaves a dash at the endOff-by-one
- Going from 100 to 150 shows -50%Logic
- Removing dashes removes only the first oneMutation and copying
- map(parseInt) turns "10" into NaN and 2Type
- AI Attempt: Remove all occurrencesLogic
- Every date shows last monthOff-by-one
- Every team ends up with every playerMutation and copying
- Switch says Saturday is a weekdayLogic
- Array sum returns 0012Type
- Status helper returns undefinedMutation and copying
- Prices over 1,000 come out as 1Type
- Order filter with global regex drops every second matchScope and closure
- Object freeze is shallow and allows nested settings mutationScope and closure
- Creating grid with array fill shares same row object referenceScope and closure
- Array fill with empty array shares same sublist instanceScope and closure
- Empty age field passes validationType
- Identical lists are reported as differentType
- Member discount never reaches the totalScope and closure
- Seat numbers come out emptyMutation and copying
- Getting the top scores reorders the original listMutation and copying
- AI Attempt: Character frequency counterNull and undefined
- Admin check says there are no adminsLogic
Hard
- Delayed double returns undefinedAsync and race conditions
- Removing duplicates never finishesInfinite loops
- Every callback reports index 3Scope and closure
- Doubling with forEach returns an empty listAsync and race conditions
- Names come back in finishing order, not input orderAsync and race conditions
- Async sum gives "[object Promise]3"Async and race conditions
- try/catch doesn't catch the divide-by-zero errorAsync and race conditions
- Adding 4 votes at once keeps only the lastAsync and race conditions
- Cached loader runs 3 times instead of onceAsync and race conditions
- 3 people book the last seatAsync and race conditions
- describe(false) can't see the global labelScope and closure
- Counter method crashes inside forEachScope and closure
- New tracker starts with the old tracker's totalScope and closure
- Search freezes when the value is missingInfinite loops
- Type checker says null is an objectType
- Two identical records counted as differentType
- Greeting says "hi null" instead of "hi guest"Null and undefined
- City lookup still crashes with ?.Null and undefined
- Page 1 shows the second page of itemsOff-by-one
- Out-of-stock item shows as availableLogic
- Adding 1 and 2 gives "1.002.00"Mutation and copying
- AI Attempt: The English ListMutation and copying
What you will practise
Questions
Does this need Node.js?
No. Your code runs in a sandboxed Web Worker in the browser, isolated from the page.
Which JavaScript do the exercises use?
Plain modern JavaScript: no frameworks, no build step. The bugs are the ones you meet in any codebase, React or Node included.
Is there a certificate?
Yes, free. Fixing 15 easy JavaScript bugs while signed in earns JavaScript Debugging · Level 1, with a verification link for LinkedIn.