|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// alright! from the sake of the function name, I can predict that it will successfully get the last digit |
| 6 | +// oh hang-on, where is the parameter???? this programmer must be tired or "coding while eating"... careful aye.. holiday is coming. |
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 | +// nope.. It runs as predicted :) xixixiixi... that way we are in this "debugging" session. |
| 21 | +// it runs but no syntax error but the output are not correct. |
| 22 | + |
18 | 23 | // Explain why the output is the way it is |
19 | 24 | // =============> write your explanation here |
| 25 | +// the function does not get any "define parameter", like nothing, so it tries to the "num" in global variable |
| 26 | +// that is given just before the function that is const num = 103; |
| 27 | +// so, every time that function is called, it will use num 103 as parameter |
| 28 | + |
20 | 29 | // Finally, correct the code to fix the problem |
21 | 30 | // =============> write your new code here |
| 31 | +const num = 103; |
| 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)}`); |
22 | 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 |
| 43 | +// no syntax error just logic error :) because, sometime we need to manipulate the function just like that. BTW that is not save anyway. |
0 commit comments