Home | HTML | Data Types | DOM | JavaScript | JS Debugging |
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
First I changed the data inside the for loop, as to obtain all of the letters, the for loop needs to iterate as many times as there is letters. alphabet.length essentially just gives how many characters are in the variable alphabet. The for loop will iterate as long as i < alphabet.length. I also changed the i in the push command to alphabet[i] as i itself is simply a placeholder for each character of the variable alphabet. To print each value stored in the variable, we need to push each character, alphabet[i], into the alphabetList array. In the end, you’ll see an array containing all the letters of the alphabet printed in the console when you run this code.
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]);
}
let letterNumber = 5
for (var i = 0; i < alphabetList.length; i++) {
if (i + 1 === letterNumber) {
console.log(alphabetList[i] + " 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
The main issue in the original code was the incorrect loop condition (i < alphabetList) and the inaccurate console output message. I changed the loop condition to (i < alphabetList.length) to iterate through all the elements of the array. The condition inside the if statement was incorrect because an array starts at 0, meaning that when i=5, the code will technically print the i+1 = 6th letter. To fix this I changed the condition to i+1 so that the if statement is satisfied when the 4th placement of the array or the 5th element of the array is reached. The console.log statement was also incorrect as it should first print the letter, alphabetList[i], and then later on the placement of the letter, letterNumber.
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
First I changed the name of the evens array to odds because the goal of the code is to print odd numbers and not even ones. Making the array named odds makes the code easier to understand. The other change I made was that I changed the initial value of i from 0 to 1. This is because the first odd number less than 10 is 1. This allows the i += 2 code to function properly by printing other odd numbers.
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? Values that are both multiples of 2 and 5 are outputted incorrectly because there is an if statement for multiples of 2 and an if statement for multiples of 5, meaning that multiples of 2 and 5 are double counted.
- Make changes to get the intended outcome. I changed the second if statement to an else if statement. This makes it so that if a number is a multiple of 5, the if statement that checks for multiples of 2 is skipped. If the number is not a multiple of 5, then the second if statement checks to see if that number is a multiple of 2. This change eliminates the double counting error.
%%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)
newNumbers.push(numbers[i])
elif (numbers[i] % 2 === 0)
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?
}
//ideally the code should support mutliple items
var selecteditem = "fries"
console.log(`Test: Selected item'${selecteditem}'`)
console.log("Expected Output: $" + menu[selecteditem].toFixed(2));
if (menu[selecteditem] !== undefined) {
total += menu[selecteditem];
}
//code should add the price of the menu items selected by the user
console.log("total: $" + total.toFixed(2));
<IPython.core.display.Javascript object>
%%js
var movies = {"Interstellar": 15.99,
"The Martian": 19.99,
"Jusrrasic Park": 4.99,
"The Shawshank Redemption": 3.99,
"The Dark Knight": 5.99,
"Star Wars: The Empire Strickes Back": 1.99,
"Avatar: The Way of Water": 7.99}
var total = 0
console.log("Movies")
for (var item in movies) {
console.log(item + " $" + movies[item].toFixed(2))
}
var selecteditem = "Avatar: The Way of Water"
console.log(` Selected item'${selecteditem}'`)
if (movies[selecteditem] !== undefined) {
total += movies[selecteditem];
}
console.log("total: $" + total.toFixed(2));
<IPython.core.display.Javascript object>
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)