Skip to content
Trace code in your head

Lesson 2.4

Why tests fail

7 min · 8 steps

  1. Step 1 of 8 · Explanation

    Tests don't read the screen. A test calls your function, takes the value it returns, and compares it with the expected value.

    Say solution(2, 3) computes const sum = a + b, then calls console.log(sum). The screen shows 5, but the function returns nothing. To the test, the result is undefined.

  2. Step 2 of 8 · Pick the approach

    The test expects 6. Your function prints 6 to the console, and the test still fails. Why?

    1. The function returns nothing, so the result is undefined
    2. The console prints 6 as a string
    3. console.log is too slow for the test
    4. The test needs console.log to be called twice
  3. Step 3 of 8 · Predict the result

    Problem "Return the sum of the digits in the string s." What does it return for "123"?

    function solution(s) {  let total = 0  for (const ch of s) {    total += ch  }  return total}
    1. "0123"
    2. 6
    3. "6"
    4. 123
  4. Step 4 of 8 · Pick the approach

    The test expects 3. Your function returns "3". Does it pass?

    1. No. Tests compare the type too, and a number isn't a string
    2. Yes, because they look the same on screen
    3. Yes, because JavaScript converts it automatically with ==
  5. Step 5 of 8 · Predict the result

    What does it return for [3, 1, 2]?

    function solution(nums) {  const sorted = nums  sorted.sort((a, b) => a - b)  return [nums[0], sorted[0]]}
    1. [1, 1]
    2. [3, 1]
    3. [3, 3]
  6. Step 6 of 8 · Find the bug

    Problem "Return a new array with every number doubled. Don't change nums." The test checks nums after the call, and it fails. Tap the line that causes it.

    function solution(nums) {  const result = nums  for (let i = 0; i < result.length; i++) {    result[i] = result[i] * 2  }  return result}
  7. Step 7 of 8 · Write the code

    solution(s)

    Return the sum of all digits in the string s, as a number.
    Constraints: 0 ≤ s.length ≤ 100, s only contains 0 to 9.

    function solution(s) {  // "123" -> 6 }
  8. Step 8 of 8 · Recap

    • Tests only see the returned value. console.log doesn't count.
    • 3 and "3" are different. A number plus a string becomes a string.
    • const b = a doesn't copy an array. Copy with [...a] before changing it.

    Pattern card

    Before you submit
    When to use it: Every time a test fails but your logic feels right. Check these three things first.
    return x          // bukan / not console.log(x)Number(ch)        // "3" -> 3const copy = [...nums]