Home HTML Data Types DOM JavaScript JS Debugging

College Board Big Idea 1

Identifying and Correcting Errors (Unit 1.4)

Become familiar with types of errors and strategies for fixing them

  • Review CollegeBoard videos and take notes on blog
  • Complete assigned MCQ questions if applicable

Code Segments

Practice fixing the following code segments!

Segment 1: Alphabet List

Intended behavior: create a list of characters from the string contained in the variable alphabet

Code:

%%js

const alphabet = "abcdefghijklmnopqrstuvwxyz";
const alphabetList = [];

for (let i = 0; i < alphabet.length; i++) {
	alphabetList.push(alphabet[i]);
}

console.log(alphabetList);
<IPython.core.display.Javascript object>

What I Changed

I changed…

  • top 2 declarations to const instead of var
  • var i = in the for loop to let i =
  • instead of waiting until i < 10, I made it iterate the entire string
  • instead of pushing the iteration number (i), I pushed the letter of alphabet at the specified iteration (alphabet[i])

Segment 2: Numbered Alphabet

Intended behavior: print the number of a given alphabet letter within the alphabet. For example:

"_" is letter number _ in the alphabet

Where the underscores (_) are replaced with the letter and the position of that letter within the alphabet (e.g. a=1, b=2, etc.)

Code:

%%js

// Copy your previous code to built alphabetList here
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const alphabetList = [];

for (let i = 0; i < alphabet.length; i++) {
	alphabetList.push(alphabet[i]);
}

let letterNumber = 5

console.log(`${alphabetList[letterNumber-1]} is letter number ${letterNumber} in the alphabet`)

// Should output:
// "e" is letter number 5 in the alphabet
<IPython.core.display.Javascript object>

What I Changed

I changed…

  • the var i = to let i =
  • removed the for loop that tried to loop the entire array to find an index
  • logged a template literal (using the backtick `)
    • I found the letter using the [ ] operator with the letterNumber - 1 inside because iterating an array starts with 0 not 1

Segment 3: Odd Numbers

Intended behavior: print a list of all the odd numbers below 10

Code:

%%js

const odds = [];
// let i = 0;

// while (i <= 10) {
//   evens.push(i);
//   i += 2;
// }
for (let i = 0; i <= 10; i++) {
  if (i % 2 == 0) {
    continue;
  }
  odds.push(i)
}

console.log(odds);
<IPython.core.display.Javascript object>

What I Changed

I changed…

  • let evens = to const oods =
  • Commented out the let i = and the while loop
    • The while loop would make it much more complicated because you would need to keep a i variable outside of it, while a for loop would have the i variable more easily acessable
  • Made a for loop that checks if the number is even (if so the loop continues/ goes to the next number). If the number is not even, it will add it to the odds array using odds.push()
    • I used (i % 2 == 0) to check if the number is even/ or evenly divisible by 2.

BELOW NOT EDITED

The intended outcome is printing a number between 1 and 100 once, if it is a multiple of 2 or 5

  • What values are outputted incorrectly. Why?
  • Make changes to get the intended outcome.
%%js

const numbers = []
const newNumbers = []
let i = 0

while (i < 100) {
    numbers.push(i)
    i += 1
}
for (let i of numbers) {
    if (numbers[i] % 5 === 0){
        newNumbers.push(numbers[i]);
        continue;
    }
    if (numbers[i] % 2 === 0){
        newNumbers.push(numbers[i]);
        continue;
    }
}
console.log(newNumbers) 


<IPython.core.display.Javascript object>

What I Changed

I changed…

  • The problem with this was that it would push numbers twice if they are divisible by both 2 and 5. For example 10 is divisible by 2 and by 5, so it would appear in the array 2 times.

  • To fix it, I added the continue; statement so that if the number fits at least 1 of the catagories, it would add it to the array, and move on to the next number.

  • Another fix would be to combine the if statements, so it checks if it is divisible by 5 OR if it is divisible by 2 in a single if statement.

Challenge

This code segment is at a very early stage of implementation.

  • What are some ways to (user) error proof this code?
  • The code should be able to calculate the cost of the meal of the user

Hint:

  • write a “single” test describing an expectation of the program of the program
  • test - input burger, expect output of burger price
  • run the test, which should fail because the program lacks that feature
  • write “just enough” code, the simplest possible, to make the test pass

Then repeat this process until you get program working like you want it to work.

%%html

<script>
    const menu =  {
        "burger": 3.99,
        "fries": 1.99,
        "drink": 0.99
        }

    //shows the user the menu and prompts them to select an item
    console.log("Menu")
    for (let item in menu) {
        console.log(item + ":  $" + menu[item].toFixed(2)) //why is toFixed used?
    }
    //ideally the code should support mutliple items
    // let items = ["burger", "fries"]

    //code should add the price of the menu items selected by the user 
    function findTotal (items) {
        let runningTotal = 0;
        items.map((item) => {
            if (!Object.keys(menu).includes(item)) {
                console.warn(`menu does not contain ${item}`);
            }
            runningTotal += menu[item]
        })
        return isNaN(runningTotal) ?  new Error('Menu has invalid item(s)'): Number(runningTotal.toFixed(2))
    }

    function testFindTotal (items, expectedOutput) {
        const output = findTotal(items)
        if (output !== expectedOutput) {
            throw new Error(`Test Failed: did not return expected output. Returned $${output} instead of $${expectedOutput}.`)
        } else {
            console.log("Test Passed")
        }
    }

    console.log("")
    console.log("--Tests--")
    console.log("ALL MENU ITEMS:")
    testFindTotal(["burger", "fries", "drink"], 6.97)
    console.log("ALL 'BURGER':")
    testFindTotal(["burger", "burger", "burger"], 11.97)
    console.log("ITEM THAT IS NOT ON THE MENU:")
    findTotal(["waffle", "burger", "fries"])

</script>

Hacks

  • Fix the errors in the first three segments in this notebook and say what you changed in the code cell under “What I Changed” (Challenge is optional)