|
1 | 1 | // Predict and explain first... |
2 | | - |
3 | 2 | // Predict the output of the following code: |
| 3 | +//The last digit of 42 is 3 |
| 4 | +//The last digit of 105 is 3 |
| 5 | +//The last digit of 806 is 3 |
4 | 6 | // =============> Write your prediction here |
| 7 | +//num is defined outside of the function, so has scope in the function getLastDigit. |
| 8 | +//the function doesn't take any arguments and uses num, so will always return 3, no matter what |
| 9 | +//is passed to the function because it will use num, which is set to 103 |
5 | 10 |
|
6 | | -const num = 103; |
| 11 | +//const num = 103; |
7 | 12 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 13 | +//function getLastDigit() { |
| 14 | +// return num.toString().slice(-1); |
| 15 | +//} |
11 | 16 |
|
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)}`); |
| 17 | +//console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 18 | +//console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 19 | +//console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 20 |
|
16 | 21 | // Now run the code and compare the output to your prediction |
17 | 22 | // =============> write the output here |
| 23 | +//The last digit of 42 is 3 |
| 24 | +//The last digit of 105 is 3 |
| 25 | +//The last digit of 806 is 3 |
18 | 26 | // Explain why the output is the way it is |
19 | 27 | // =============> write your explanation here |
| 28 | +// As I predicted, for the reason above |
20 | 29 | // Finally, correct the code to fix the problem |
21 | 30 | // =============> write your new code here |
22 | 31 |
|
| 32 | +function getLastDigit(num) { |
| 33 | + return num.toString().slice(-1); |
| 34 | +} |
| 35 | + |
| 36 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 37 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 38 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 39 | + |
23 | 40 | // This program should tell the user the last digit of each number. |
24 | 41 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments