|
1 | 1 | // Predict and explain first... |
2 | | - |
3 | 2 | // Predict the output of the following code: |
4 | 3 | // =============> Write your prediction here |
| 4 | +// Prediction: All three lines print "3" because getLastDigit has no parameter |
| 5 | +// and always uses the outer const num = 103 (last digit 3). The arguments |
| 6 | +// 42, 105, and 806 are ignored. |
5 | 7 |
|
6 | | -const num = 103; |
7 | 8 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 9 | +//const num = 103; |
| 10 | + |
| 11 | +//function getLastDigit() { |
| 12 | +// return num.toString().slice(-1); |
| 13 | +//} |
| 14 | + |
| 15 | +//console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 16 | +//console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 17 | +//console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
11 | 18 |
|
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)}`); |
15 | 19 |
|
16 | 20 | // Now run the code and compare the output to your prediction |
17 | 21 | // =============> write the output here |
| 22 | +// The last digit of 42 is 3 |
| 23 | +// The last digit of 105 is 3 |
| 24 | +// The last digit of 806 is 3 |
| 25 | + |
18 | 26 | // Explain why the output is the way it is |
19 | 27 | // =============> write your explanation here |
| 28 | +// getLastDigit() does not declare a parameter, so the values passed in |
| 29 | +// (42, 105, 806) are not available inside the function. It reads the |
| 30 | +// global num (103) every time, so slice(-1) always returns "3". |
| 31 | + |
20 | 32 | // Finally, correct the code to fix the problem |
21 | 33 | // =============> write your new code here |
22 | | - |
23 | 34 | // This program should tell the user the last digit of each number. |
24 | 35 | // Explain why getLastDigit is not working properly - correct the problem |
| 36 | + |
| 37 | +function getLastDigit(num) { |
| 38 | + return num.toString().slice(-1); |
| 39 | +} |
| 40 | + |
| 41 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 42 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 43 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
0 commit comments