|
1 | 1 | // Predict and explain first... |
| 2 | +// This code is intended to find the last digit of a number, but it has a bug. |
2 | 3 |
|
3 | 4 | // Predict the output of the following code: |
| 5 | +// Predict the output of the following code is '3' for the input 103. since the last digit of 103 is 3 and it is a global variable, so regardless of the input, it will always return the last digit of the global variable `num` which is 103. |
4 | 6 | // =============> Write your prediction here |
5 | 7 |
|
6 | | -const num = 103; |
| 8 | +// const num = 103; |
7 | 9 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 10 | +// function getLastDigit() { |
| 11 | +// return num.toString().slice(-1); |
| 12 | +// } |
11 | 13 |
|
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)}`); |
15 | 17 |
|
16 | 18 | // Now run the code and compare the output to your prediction |
| 19 | +// The last digit of 42 is 3 |
| 20 | +// The last digit of 105 is 3 |
| 21 | +// The last digit of 806 is 3 |
| 22 | + |
17 | 23 | // =============> write the output here |
18 | 24 | // Explain why the output is the way it is |
19 | 25 | // =============> write your explanation here |
| 26 | +// The output is always '3' because the function `getLastDigit` is using a global variable `num` which is set to 103 |
20 | 27 | // Finally, correct the code to fix the problem |
21 | 28 | // =============> write your new code here |
22 | | - |
| 29 | +function getLastDigit(num) { |
| 30 | + return num.toString().slice(-1); |
| 31 | +} |
| 32 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 33 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 34 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
23 | 35 | // This program should tell the user the last digit of each number. |
24 | 36 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments