|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | | -// =============> Write your prediction here |
| 4 | +// It will return the last digit of the number 103 which is 3 because the function getLastDigit is using the variable num which is set |
| 5 | +// in the const num = 103; and not the parameter passed to the function getLastDigit. |
5 | 6 |
|
6 | | -const num = 103; |
| 7 | +/*const num = 103; |
7 | 8 |
|
8 | 9 | function getLastDigit() { |
9 | 10 | return num.toString().slice(-1); |
10 | 11 | } |
11 | 12 |
|
12 | 13 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 14 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | | -console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 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 | | -// =============> write the output here |
| 18 | +// =============> The last digit of 42 is 3 |
| 19 | +//The last digit of 105 is 3 |
| 20 | +// The last digit of 806 is 3 |
| 21 | + |
18 | 22 | // Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
| 23 | +// =============> as explained above, the const num = 103; is being used in the function getLastDigit instead of the parameter passed to the function. |
20 | 24 | // Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
22 | 25 |
|
23 | | -// This program should tell the user the last digit of each number. |
24 | | -// Explain why getLastDigit is not working properly - correct the problem |
| 26 | +function getLastDigit(num) { |
| 27 | + return num.toString().slice(-1); |
| 28 | +} |
| 29 | + |
| 30 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 31 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 32 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 33 | + |
| 34 | + |
0 commit comments