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

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

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

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

What I Changed

I changed the i < 10 in the for loop to i < alphabet.length to let it iterate over the entire alphabet, not just the first 10 characters.

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
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var alphabetList = [];

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

var letterNumber = 5;

var letter = alphabetList[letterNumber - 1];
console.log(letter + " is letter number " + letterNumber + " in the alphabet");

<IPython.core.display.Javascript object>

What I Changed

I changed:

  • Removed unecessary for loop
  • Logged the letter and number, not the number twice
  • Modified code to fit with any number, it was previoulsy hardcoded for 5

Segment 3: Odd Numbers

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

Code:

%%js

let odds = [];
let i = 1;

while (i <= 10) {
  odds.push(i);
  i += 2;
}
console.log(odds);
<IPython.core.display.Javascript object>

What I Changed

I changed the initial value of i to be 1 instead of 0. Since it was 0, it was prinitng all the even numbers, not odd. I also modified the variable name from evens to odds to make it clear.

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

var numbers = []
var newNumbers = []
var i = 0

while (i < 100) {
    numbers.push(i)
    i += 1
}
for (var i of numbers) {
    if (numbers[i] % 5 === 0 || numbers[i] % 2 === 0) // Make one command in order to only print once, use || for OR logical operation
        newNumbers.push(numbers[i])
}
console.log(newNumbers) 


<IPython.core.display.Javascript object>

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.

%%js

var menu =  {"burger": 3.99,
         "fries": 1.99,
         "drink": 0.99}
var total = 0;

//shows the user the menu and prompts them to select an item
console.log("Menu")
for (var item in menu) {
    console.log(item + "  $" + menu[item].toFixed(2)) //why is toFixed used? Used for decimal places, very cool
}
//ideally the code should support mutliple items (I sense a misspelling in this sentence, do you?)
var keep_going = 'N';
var order_list = {
    '1': 0,
    '2': 0,
    '3': 0
};
while (keep_going == 'N') {
    prompt("Would you like a burger (1), some fries (2), or a drink (3)?")
    order_list[temp] += parseInt(prompt("How many would you like?"))
    var keep_going = prompt("Is that it for today? [Y/N]").toUpperCase() //the toUpperCase makes sure a lowercase y or n is still accepted
}


//code should add the price of the menu items selected by the user 
total += menu['burger'] * order_list['1']
total += menu['fries'] * order_list['2']
total += menu['drink'] * order_list['3']

total *= 1.0725
var tip = parseInt(prompt("Please put the amount in $ that you would like to tip: "))

console.log('$' + total.toFixed(1) + tip)
<IPython.core.display.Javascript object>

ChatGPT Review

Pros:

  1. User-Friendly: The code is user-friendly, as it provides a clear menu and prompts the user for their orders, making the ordering process straightforward.

  2. Modular: It breaks down the logic into manageable sections, such as menu initialization, order tracking, and calculating the total. This makes it easier to understand and maintain.

  3. Error Handling: The code attempts to handle lowercase ‘y’ and ‘n’ inputs by converting them to uppercase, ensuring consistency.

Areas for Improvement:

  1. Validation: The code lacks input validation. It assumes that the user will always enter valid choices and quantities. It would be better to include validation to handle cases where the user enters non-numeric quantities or selects invalid menu items.

  2. Comments: While there are comments in the code, some comments could be more descriptive. For example, comments could explain the purpose of specific calculations or the reason behind using certain constants (e.g., 1.0725 for tax).

  3. Code Reusability: The code is designed for a specific menu with three items (burger, fries, and drink) and hardcoded keys in the order_list. To make it more versatile, you could allow for dynamic menu creation, where the menu items and their prices are stored in an array or another data structure, allowing for a variable number of items.

  4. Error Handling: In case the user enters an invalid menu choice or quantity, it would be beneficial to provide feedback and give the user a chance to correct their input rather than potentially causing errors.

  5. Modular Functions: Consider breaking down the code into smaller, reusable functions. For example, you could have separate functions for displaying the menu, taking orders, calculating totals, and handling tax and tips. This would make the code more organized and easier to test and maintain.

  6. Output Formatting: The final output of the total could benefit from more descriptive formatting. For instance, you could include labels to specify the subtotal, tax amount, tip amount, and the final total.

  7. Error Handling for Tip Input: The code assumes the user will enter a valid integer for the tip. Adding input validation and error handling for the tip input would make the code more robust.

  8. Currency Formatting: Depending on the locale, it’s advisable to use proper currency formatting functions to display currency values, especially when dealing with user input for money.

Overall, the code provides a good starting point for a simple menu ordering system but could benefit from enhancements to handle user input errors, offer more flexibility, and provide improved feedback and formatting for the final total.

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)