|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// i think the function won't return anything for numbers 42, 105 and 806 because the variable num contains value 103 and the return will only |
| 6 | +// work with 103 inside the function. There is no relation between const num = 103; and 42, 105 and 806. |
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 output: |
| 21 | +// The last digit of 42 is 3 |
| 22 | +// The last digit of 105 is 3 |
| 23 | +// The last digit of 806 is 3 |
| 24 | + |
18 | 25 | // Explain why the output is the way it is |
19 | 26 | // =============> write your explanation here |
| 27 | +// The output is quite similar to my prediction. When the function tried to find out function calls for getLastDigit(42), getLastDigit(105) |
| 28 | +// and getLastDigit(806) it doesn't find any of these because those didn't match with the variable declaration. As the function wokred only |
| 29 | +// with 103, it returned value for 103 and printed 3 as last digit for all three values. |
20 | 30 | // Finally, correct the code to fix the problem |
21 | 31 | // =============> write your new code here |
| 32 | +// The correct code: |
| 33 | + |
| 34 | +function getLastDigit(num) { |
| 35 | + return num.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)}`); |
22 | 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 |
0 commit comments