|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// The output will be: |
| 6 | +// The last digit of 42 is 3 |
| 7 | +// The last digit of 105 is 3 |
| 8 | +// The last digit of 806 is 3 |
| 9 | +// |
| 10 | +// This happens because the function `getLastDigit` doesn’t use the argument passed to it. |
| 11 | +// Instead, it always refers to the constant `num = 103`, |
| 12 | +// so every time you call it, it converts 103 to a string and returns the last digit ("3"). |
5 | 13 |
|
6 | | -const num = 103; |
| 14 | +// Now run the code and compare the output to your prediction |
| 15 | +// =============> write the output here |
| 16 | +// The last digit of 42 is 3 |
| 17 | +// The last digit of 105 is 3 |
| 18 | +// The last digit of 806 is 3 |
| 19 | + |
| 20 | +// Explain why the output is the way it is |
| 21 | +// =============> write your explanation here |
| 22 | +// The function `getLastDigit` ignores the argument being passed (like 42, 105, or 806) |
| 23 | +// because it doesn’t have a parameter defined. |
| 24 | +// Instead, it always uses the globally defined constant `num` (which is 103). |
| 25 | +// Therefore, the function always returns the last digit of 103, which is "3". |
7 | 26 |
|
8 | | -function getLastDigit() { |
| 27 | +// Finally, correct the code to fix the problem |
| 28 | +// =============> write your new code here |
| 29 | +function getLastDigit(num) { |
9 | 30 | return num.toString().slice(-1); |
10 | 31 | } |
11 | 32 |
|
12 | 33 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 34 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | 35 | console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 36 |
|
16 | | -// Now run the code and compare the output to your prediction |
17 | | -// =============> write the output here |
18 | | -// Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
20 | | -// Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
22 | | - |
23 | 37 | // This program should tell the user the last digit of each number. |
24 | 38 | // Explain why getLastDigit is not working properly - correct the problem |
| 39 | +// The function was not working because it didn’t accept any parameters and |
| 40 | +// was instead using the fixed global variable `num`. |
| 41 | +// By adding a parameter to the function and using that instead, |
| 42 | +// it now correctly calculates the last digit for any input number. |
| 43 | + |
0 commit comments