|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// =============> Prediction: The code will print '3' for all three log statements instead of '2', '5', and '6'. |
5 | 6 |
|
6 | | -const num = 103; |
| 7 | +// const num = 103; |
7 | 8 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 9 | +// function getLastDigit() { |
| 10 | +// return num.toString().slice(-1); |
| 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 ${getLastDigit(42)}`); |
| 14 | +// console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 15 | +// console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 16 |
|
16 | 17 | // Now run the code and compare the output to your prediction |
17 | 18 | // =============> 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 | + |
18 | 22 | // Explain why the output is the way it is |
19 | 23 | // =============> 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 | + |
20 | 27 | // 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. |
21 | 30 | // =============> write your new code here |
22 | 31 |
|
| 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 | + |
23 | 42 | // This program should tell the user the last digit of each number. |
24 | 43 | // Explain why getLastDigit is not working properly - correct the problem |
| 44 | + |
| 45 | + |
0 commit comments