Skip to content

Commit e214e89

Browse files
- Fix getLastDigit function to accept a parameter and return the correct last digit
- Predict and explain hardcoded global variable behavior before fixing
1 parent b800220 commit e214e89

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+
// =============> Prediction: The code will print '3' for all three log statements instead of '2', '5', and '6'.
56

6-
const num = 103;
7+
// const num = 103;
78

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

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)}`);
13+
// console.log(`The last digit of 42 is ${getLastDigit(42)}`);
14+
// console.log(`The last digit of 105 is ${getLastDigit(105)}`);
15+
// console.log(`The last digit of 806 is ${getLastDigit(806)}`);
1516

1617
// Now run the code and compare the output to your prediction
1718
// =============> write the output here
19+
20+
// =============> Output: The last digit of 42 is 3 The last digit of 105 is 3 The last digit of 806 is 3
21+
1822
// Explain why the output is the way it is
1923
// =============> write your explanation here
24+
25+
// =============> Explanation: The function getLastDigit() was defined without parameters, so JavaScript ignored the arguments (42, 105, 806) passed during the function calls. Instead, the function continuously accessed the global variable num (103), converted it to a string, and sliced off the last character ('3') every time.
26+
2027
// Finally, correct the code to fix the problem
28+
29+
// =============> Fix: Pass a parameter into getLastDigit so it receives the inputs, and use that parameter inside the function body instead of the outer variable.
2130
// =============> write your new code here
2231

32+
// const num = 103;
33+
34+
function getLastDigit(num) {
35+
return num.toString().slice(-1);
36+
}
37+
38+
console.log(`The last digit of 42 is ${getLastDigit(42)}`); // output The last digit of 42 is 2
39+
console.log(`The last digit of 105 is ${getLastDigit(105)}`); // output The last digit of 105 is 5
40+
console.log(`The last digit of 806 is ${getLastDigit(806)}`); // output The last digit of 806 is 6
41+
2342
// This program should tell the user the last digit of each number.
2443
// Explain why getLastDigit is not working properly - correct the problem
44+
45+

0 commit comments

Comments
 (0)