When you see the error below, there are a few things to note!
This is a good opportunity to practice tracing code. If you are sure that a function is correct, but it is not returning the proper values, check ALL of the functions that are CALLED within the original function!
Whenever a function is called, we skip up to that function call's definition and execute THAT code before returning to our original call...If something is wrong in any of the functions that are utilized in your original function, it will throw everything off!
Example:
let findSum = (x: number, y: number, z: number): number => {
return x + y - z;
}
let find average = (a: number, b: number, c: number): number => {
let sumOfAll: number = findSum(a, b, c);
let answer: number = sumOfAll / 3;
return answer;
}
print(average(10, 15, 20));
//wheres the error?
When we call average(10,15,20), the wrong value will be printed...why?
Although the average function is correct, we see that the findSum function is incorrect...since it is called within the average function, the calculation will be incorrect! Use this logic in your own work!
We have used 'print' statements to display our final answers...but we can use them elsewhere too!
Every time the value you are calculating changes, try printing that current value. Is what is being printed what is expected? Using this debugging technique, you can pinpoint the exact line that something goes wrong!
Example:
let calculateSlope = (x1: number, x2: number, y1: number, y2: number): number => {
let yTotal: number = y2 - y1;
print(yTotal);
let xTotal: number = x2 - x1;
print(xTotal);
let slope: number = yTotal / xTotal;
print(slope);
return slope;
}
//notice that after every step, we print the value that was changed
//this way, we can find THE EXACT LINE that has an error
The blank screen of death is usually a sign that there’s an infinite loop somewhere in your program.
Infinite while loops
// the counter 'i' is declared outside of the loop
let i: number = 0;
while (i < 10) {
print("It was a dark and stormy night, and Jeffrey said to Kris..");
print(" 'Kris, tell us a story..' ");
print("and so Kris began....");
/* Because 'i' is not incremented inside the loop, it will never be greater
than or equal to 10, therefore the loop will never end, and Kris will be
telling a story forever! */
}
Therefore, make sure the loop is incremented!
let i: number = 0;
while (i < 10) {
print("It was a dark and stormy night, and Jeffrey said to Kris..");
print(" 'Kris, tell us a story..' ");
print("and so Kris began....");
i++;
// i++ is shorthand for i = i + 1
}
This way, Jeffrey will only hear the story 10 times. (Always keep them wanting more!)