|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
5 | | - |
6 | | -const num = 103; |
| 5 | +//I think const being declared before function may cause a problem on returning num value (line 10) |
7 | 6 |
|
8 | 7 | function getLastDigit() { |
| 8 | + const num = 103; |
9 | 9 | return num.toString().slice(-1); |
10 | 10 | } |
11 | | - |
12 | 11 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 12 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | 13 | console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 14 |
|
16 | 15 | // Now run the code and compare the output to your prediction |
17 | 16 | // =============> write the output here |
| 17 | +// My prediction was close regarding line 10 as the value of num is not returned. |
18 | 18 | // Explain why the output is the way it is |
19 | 19 | // =============> write your explanation here |
| 20 | +// The code has returned 3 as the last digit for all provided numbers because num value is restricted to 103 as value and can't be used outside the function |
| 21 | +// Also function getLastDigit() has no parameter set |
20 | 22 | // Finally, correct the code to fix the problem |
21 | 23 | // =============> write your new code here |
22 | 24 |
|
| 25 | +function getLastDigit(num) { |
| 26 | + return num.toString().slice(-1); |
| 27 | +} |
| 28 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 29 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 30 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 31 | + |
23 | 32 | // This program should tell the user the last digit of each number. |
24 | 33 | // Explain why getLastDigit is not working properly - correct the problem |
| 34 | +// getLastDigit was no working as variable num was taking precedence |
0 commit comments