|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// The output will always be 3 |
5 | 6 |
|
6 | 7 | const num = 103; |
7 | 8 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 9 | +// function getLastDigit() { |
| 10 | +// return num.toString().slice(-1); |
| 11 | +// } |
11 | 12 |
|
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)}`); |
| 13 | +// console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 14 | +// console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 15 | +// console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 16 |
|
16 | 17 | // Now run the code and compare the output to your prediction |
17 | 18 | // =============> write the output here |
| 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 does not take an argument, so supplying one is no use. |
| 26 | +// Since there is no num variable inside the function, it looks for it in the nearest enclosing scope. |
| 27 | +// It finds num = 103, so it will always operate on that variable |
| 28 | + |
20 | 29 | // Finally, correct the code to fix the problem |
21 | 30 | // =============> write your new code here |
| 31 | +function getLastDigit(num) { |
| 32 | + return num.toString().slice(-1); |
| 33 | +} |
| 34 | + |
| 35 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 36 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 37 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
22 | 38 |
|
23 | 39 | // This program should tell the user the last digit of each number. |
24 | 40 | // Explain why getLastDigit is not working properly - correct the problem |
| 41 | +// ??? it returns the last digit |
0 commit comments