|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +//the output will be: an error because the function getLastDigit is not defined to take any parameters, but we are trying to pass a number as an argument when we call the function. The error message will likely indicate that getLastDigit is not a function or that it cannot be called with arguments. |
| 6 | +//const num = 103; |
5 | 7 |
|
6 | | -const num = 103; |
| 8 | +//function getLastDigit() { |
| 9 | + //return num.toString().slice(-1); |
| 10 | +//} |
7 | 11 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
11 | | - |
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)}`); |
| 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 | 15 |
|
16 | 16 | // Now run the code and compare the output to your prediction |
17 | 17 | // =============> write the output here |
| 18 | +//it does run but returns the last digit of the number 103 for all three calls to getLastDigit, which is not the expected behavior. The output will be: |
| 19 | +// The last digit of 42 is 3 |
| 20 | +// The last digit of 105 is 3 |
| 21 | +// The last digit of 806 is 3 |
| 22 | + |
18 | 23 | // Explain why the output is the way it is |
19 | 24 | // =============> write your explanation here |
| 25 | +// The function getLastDigit is not taking any parameters, so it always returns the last digit of the global variable 'num', which is 103. The function should take a number as a parameter and return the last digit of that number. |
| 26 | + |
20 | 27 | // Finally, correct the code to fix the problem |
21 | 28 | // =============> write your new code here |
| 29 | +function getLastDigit(num) { |
| 30 | + return num.toString().slice(-1); |
| 31 | +} |
| 32 | + |
| 33 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 34 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 35 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
22 | 36 |
|
23 | 37 | // This program should tell the user the last digit of each number. |
24 | 38 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments