|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | | -// =============> Write your prediction here |
| 4 | +// Prediction: Each line reports 103's last digit (3), because getLastDigit |
| 5 | +// ignores its arguments and always reads the global num variable. |
5 | 6 |
|
6 | 7 | const num = 103; |
7 | 8 |
|
8 | | -function getLastDigit() { |
| 9 | +function getLastDigitBeforeFix() { |
9 | 10 | return num.toString().slice(-1); |
10 | 11 | } |
11 | 12 |
|
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 ${getLastDigitBeforeFix(42)}`); |
| 14 | +console.log(`The last digit of 105 is ${getLastDigitBeforeFix(105)}`); |
| 15 | +console.log(`The last digit of 806 is ${getLastDigitBeforeFix(806)}`); |
15 | 16 |
|
16 | 17 | // Now run the code and compare the output to your prediction |
17 | | -// =============> write the output here |
| 18 | +// Output: Each line reports 3. |
18 | 19 | // Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
| 20 | +// Explanation: getLastDigit has no parameter and reads the unchanged global |
| 21 | +// num (103), so passing 42, 105, or 806 has no effect. |
20 | 22 | // Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
| 23 | +function getLastDigit(number) { |
| 24 | + return number.toString().slice(-1); |
| 25 | +} |
| 26 | + |
| 27 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 28 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 29 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
22 | 30 |
|
23 | 31 | // This program should tell the user the last digit of each number. |
24 | 32 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments