|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | | -// =============> The output will be: |
5 | | -// 1. The last digit of 42 is 3 |
6 | | -// 2. The last digit of 105 is 3 |
7 | | -// 3. The last digit of 806 is 3 |
8 | | -// Why? Because we don't pass any parameter to the function ant it always uses the variable "num", which defined in the global scope, so function has access to it and the last digit of 103 is 3. |
| 4 | +// =============> Write your prediction here |
9 | 5 |
|
10 | | -// const num = 103; |
| 6 | +const num = 103; |
11 | 7 |
|
12 | | -// function getLastDigit() { |
13 | | -// return num.toString().slice(-1); |
14 | | -// } |
| 8 | +function getLastDigit() { |
| 9 | + return num.toString().slice(-1); |
| 10 | +} |
15 | 11 |
|
16 | | -// console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
17 | | -// console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
18 | | -// console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 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)}`); |
19 | 15 |
|
20 | 16 | // Now run the code and compare the output to your prediction |
21 | | -// =============> The last digit of 42 is 3 |
22 | | -// The last digit of 105 is 3 |
23 | | -// The last digit of 806 is 3 |
| 17 | +// =============> write the output here |
24 | 18 | // Explain why the output is the way it is |
25 | | -// =============> Because we use the global variable "num" in the function instead of passing the parameter to the function. |
| 19 | +// =============> write your explanation here |
26 | 20 | // Finally, correct the code to fix the problem |
| 21 | +// =============> write your new code here |
27 | 22 |
|
28 | | -function getLastDigit(num) { |
29 | | - return num.toString().slice(-1); |
30 | | -} |
31 | | -console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
32 | | -console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
33 | | -console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
34 | | -// |
35 | 23 | // This program should tell the user the last digit of each number. |
36 | | -// |
37 | | -// Now output looks correctly: |
38 | | -// The last digit of 42 is 2 |
39 | | -// The last digit of 105 is 5 |
40 | | -// The last digit of 806 is 6 |
41 | | -// |
42 | 24 | // Explain why getLastDigit is not working properly - correct the problem |
43 | | -// Actually, maybe its not the good idea to use the same name "num" for different variables in different scopes, because it can be confusing. It works correctly but next time I'll use for the global scope some more meaningful name. |
0 commit comments