|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// The output should always be 3 because the parameter is not defined in the function, |
| 6 | +// and the variable num is always 103 in the global scope. |
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 | 14 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 15 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | 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 | +/* |
| 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 | +*/ |
| 25 | +// As expected, the output is always 3. |
| 26 | + |
18 | 27 | // Explain why the output is the way it is |
19 | 28 | // =============> write your explanation here |
| 29 | +//The num is defined in the global scope as 103. |
| 30 | +// And the function does not accept any parameters. |
| 31 | +// So every time the function is called, it returns the last digit of 103, which is 3. |
| 32 | + |
20 | 33 | // Finally, correct the code to fix the problem |
21 | 34 | // =============> write your new code here |
| 35 | +function getLastDigit(num) { |
| 36 | + return num.toString().slice(-1); |
| 37 | +} |
| 38 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); // should return 2 |
| 39 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); // should return 5 |
| 40 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); // should return 6 |
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