|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | | -// =============> Write your prediction here |
| 4 | +// =============> In my knowledge only the output from line 6 will be printed correctly. As for line 12, 13, and 14 it will throw error or will print undefined as we don't declare any variable for them but only value. |
5 | 5 |
|
6 | | -const num = 103; |
| 6 | +// const num = 103; |
7 | 7 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
| 8 | +// function getLastDigit() { |
| 9 | +// return num.toString().slice(-1); |
| 10 | +// } |
11 | 11 |
|
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)}`); |
| 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)}`); |
15 | 15 |
|
16 | 16 | // Now run the code and compare the output to your prediction |
17 | | -// =============> write the output here |
| 17 | +// =============> the output after running the code is: ---The last digit of 42 is 3 --- The last digit of 105 is 3 --- The last digit of 806 is 3; |
| 18 | +// my prediction was half correct as it worked only with line 6 but it did not throw error or undefined. here not syntax error but logical error. |
| 19 | + |
18 | 20 | // Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
| 21 | +// =============> Its because JavaScript only calls the function 3 times, it does not read or ignore the value inside as they are not declared. |
| 22 | + |
20 | 23 | // Finally, correct the code to fix the problem |
21 | 24 | // =============> write your new code here |
| 25 | +function getLastDigit(num) { |
| 26 | + return num.toString().slice(-1); |
| 27 | +} |
| 28 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 29 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 30 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
22 | 31 |
|
23 | 32 | // This program should tell the user the last digit of each number. |
24 | 33 | // Explain why getLastDigit is not working properly - correct the problem |
| 34 | +// ===> it was not working with line 12, 13, and 14 because we had not declared the variable inside the function parameter, to fix the issue is to declare the num variable inside the parameter of the function. and remove the const variable of num above the function or line 6. |
0 commit comments