|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +//ok the issue is clear, const is used to initialise the variable num |
| 6 | +//at the same time num supposed to take several inputs or change its inputs |
| 7 | +//to get the last digit of each number. However, its declared before the function using const so its value can't be reassigned |
| 8 | +//so I'm assuming its value will always be excuted in the calculation |
5 | 9 |
|
6 | | -const num = 103; |
| 10 | +//const num = 103; |
7 | 11 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 12 | +//function getLastDigit() { |
| 13 | +//return num.toString().slice(-1); |
| 14 | +//} |
11 | 15 |
|
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)}`); |
| 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)}`); |
15 | 19 |
|
16 | 20 | // Now run the code and compare the output to your prediction |
17 | 21 | // =============> write the output here |
| 22 | +//The last digit of 42 is 3 |
| 23 | +//The last digit of 105 is 3 |
| 24 | +//The last digit of 806 is 3 |
18 | 25 | // Explain why the output is the way it is |
19 | 26 | // =============> write your explanation here |
| 27 | +//Because num was declared as a constant value 103 , so the assigned value of num is 103 |
| 28 | + |
| 29 | +//so out output of the last digit will calculate num when the input is 103 only |
| 30 | +//no matter how many numbers we include in the brackets, the excution of the function depend on the declared num value |
| 31 | +//num is declared with const and has the value 103 |
| 32 | +//the solution is to declare num as a parameter inside the function |
20 | 33 | // Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
| 34 | +// ===========> write your new code here |
22 | 35 |
|
| 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)}`); |
23 | 43 | // This program should tell the user the last digit of each number. |
24 | 44 | // Explain why getLastDigit is not working properly - correct the problem |
| 45 | +//because the declared declared variable num is assigned a constant value 103. |
| 46 | +//the solution is to delete the loine before the function and declare num as a parameter inside the function |
0 commit comments