|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +//getLastDigit will convert a number to a string and reverse it |
| 6 | +// However, since there is no parameter or local variable we might run into an Error |
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)}`); |
15 | 17 |
|
16 | 18 | // Now run the code and compare the output to your prediction |
17 | 19 | // =============> write the output here |
| 20 | +// The last digit of 42 is 3 |
| 21 | +// The last digit of 105 is 3 |
| 22 | +// The last digit of 806 is 3 |
18 | 23 | // Explain why the output is the way it is |
19 | 24 | // =============> write your explanation here |
| 25 | +// As expected, the function has no parameters, so it relies on the global variable "num" as its only variable. |
| 26 | +// Since there are no parameters defined, the function permanently uses the global variable instead. |
| 27 | +// This means even if we pass arguments when calling the function, they will be ignored because there are no parameters to receive them. |
| 28 | + |
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 | + |
| 40 | + |
23 | 41 | // This program should tell the user the last digit of each number. |
24 | 42 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments