|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// A: The function supposed to print the last digit of 42, 105 and 806 which is 2, 5, 6. But the function could not run smooth |
| 6 | +// because of the variable "num" has been declared. |
5 | 7 |
|
6 | | -const num = 103; |
| 8 | +//const num = 103; |
7 | 9 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 10 | +//function getLastDigit() { |
| 11 | +// return num.toString().slice(-1); |
| 12 | +//} |
11 | 13 |
|
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)}`); |
| 14 | +//console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 15 | +//console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 16 | +//console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 17 | + |
| 18 | +// This program should tell the user the last digit of each number. |
| 19 | +// Explain why getLastDigit is not working properly - correct the problem |
15 | 20 |
|
16 | 21 | // Now run the code and compare the output to your prediction |
17 | 22 | // =============> write the output here |
| 23 | +//A: The last digit of 42 is 3 |
| 24 | +//The last digit of 105 is 3 |
| 25 | +//The last digit of 806 is 3 |
| 26 | + |
18 | 27 | // Explain why the output is the way it is |
19 | 28 | // =============> write your explanation here |
| 29 | +// A: because num has been declared for 103 so the function could only get the last digit of 42, 105 and 806. |
| 30 | + |
20 | 31 | // Finally, correct the code to fix the problem |
21 | 32 | // =============> write your new code here |
22 | 33 |
|
| 34 | +function getLastDigit(number) { |
| 35 | + return number.toString().slice(-1); |
| 36 | +} |
| 37 | + |
| 38 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 39 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 40 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 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 | +// A: it is because num has been strictly declared as 103 before. and the value is console log could be be applied to function. |
| 45 | +// To fix this parameter of getLastDigit should assign for val as a placeholder to allow different value |
0 commit comments