|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// I predict that the three console.log messages will always output 3. |
| 6 | +// This is due to the fact that the const num is defined as 103 and the program will always use that global value as the source of truth. |
5 | 7 |
|
6 | 8 | const num = 103; |
7 | 9 |
|
8 | 10 | function getLastDigit() { |
9 | 11 | return num.toString().slice(-1); |
10 | 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 |
| 23 | + |
18 | 24 | // Explain why the output is the way it is |
19 | 25 | // =============> write your explanation here |
| 26 | +// The global value that is defined outside of the function is used as the source of truth. |
| 27 | +// Therefore when the program executes the line return num.toString().slice(-1); it always considers the global value. |
| 28 | +// The console.log ignores the values. |
| 29 | + |
20 | 30 | // Finally, correct the code to fix the problem |
21 | 31 | // =============> write your new code here |
22 | 32 |
|
| 33 | +function getLastDigit(num) { |
| 34 | + return num.toString().slice(-1); |
| 35 | +} |
| 36 | + |
| 37 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 38 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 39 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 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