|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// Nothing is going to run properly because the function does not have any parameters. |
| 6 | +// I think everything will get a syntax error |
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 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 | +// I was wrong in my prediction. Code runs. |
| 27 | +// It says the last digit is 3 for every number which is wrong |
| 28 | +// This is because we declared the var num = 103 globally, and it is affecting all the fucntion calls |
| 29 | +// Because of the global declaration, every function call is going to use the global num |
| 30 | +// This is bad because the code is now taking in diferent parameters but returning a value based on one global value. |
| 31 | +// TO fix this we remove the global var num. |
| 32 | +// Then we add num as a parameter in the function :getLastDigit(num) |
| 33 | + |
20 | 34 | // Finally, correct the code to fix the problem |
21 | 35 | // =============> write your new code here |
| 36 | +function getLastDigit(num) { |
| 37 | + return num.toString().slice(-1); |
| 38 | +} |
| 39 | + |
| 40 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 41 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 42 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
22 | 43 |
|
23 | 44 | // This program should tell the user the last digit of each number. |
24 | 45 | // Explain why getLastDigit is not working properly - correct the problem |
0 commit comments