Skip to content

Commit 595728f

Browse files
committed
Predicted, explained and fixed code errors
1 parent cf34a26 commit 595728f

1 file changed

Lines changed: 28 additions & 7 deletions

File tree

  • Sprint-3/2-mandatory-debug

‎Sprint-3/2-mandatory-debug/2.js‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,44 @@
22

33
// Predict the output of the following code:
44
// =============> Write your prediction here
5+
// Nothing is going to run properly because the function does not have any parameters.
6+
// I think everything will get a syntax error
57

6-
const num = 103;
8+
// const num = 103;
79

8-
function getLastDigit() {
9-
return num.toString().slice(-1);
10-
}
10+
// function getLastDigit() {
11+
// return num.toString().slice(-1);
12+
// }
1113

12-
console.log(`The last digit of 42 is ${getLastDigit(42)}`);
13-
console.log(`The last digit of 105 is ${getLastDigit(105)}`);
14-
console.log(`The last digit of 806 is ${getLastDigit(806)}`);
14+
// console.log(`The last digit of 42 is ${getLastDigit(42)}`);
15+
// console.log(`The last digit of 105 is ${getLastDigit(105)}`);
16+
// console.log(`The last digit of 806 is ${getLastDigit(806)}`);
1517

1618
// Now run the code and compare the output to your prediction
1719
// =============> write the output here
20+
// The last digit of 42 is 3
21+
// The last digit of 105 is 3
22+
// The last digit of 806 is 3
23+
1824
// Explain why the output is the way it is
1925
// =============> write your explanation here
26+
// I was wrong in my prediction. Code runs.
27+
// It says the last digit is 3 for every number which is wrong
28+
// This is because we declared the var num = 103 globally, and it is affecting all the fucntion calls
29+
// Because of the global declaration, every function call is going to use the global num
30+
// This is bad because the code is now taking in diferent parameters but returning a value based on one global value.
31+
// TO fix this we remove the global var num.
32+
// Then we add num as a parameter in the function :getLastDigit(num)
33+
2034
// Finally, correct the code to fix the problem
2135
// =============> write your new code here
36+
function getLastDigit(num) {
37+
return num.toString().slice(-1);
38+
}
39+
40+
console.log(`The last digit of 42 is ${getLastDigit(42)}`);
41+
console.log(`The last digit of 105 is ${getLastDigit(105)}`);
42+
console.log(`The last digit of 806 is ${getLastDigit(806)}`);
2243

2344
// This program should tell the user the last digit of each number.
2445
// Explain why getLastDigit is not working properly - correct the problem

0 commit comments

Comments
 (0)