|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
| 3 | + |
3 | 4 | // Predict the output of the following code: |
4 | | -// =============> Write your prediction here |
| 5 | +// =============> the function is going to return error as the /1 is not valid expression or syntax |
| 6 | + |
5 | 7 |
|
6 | 8 | const num = 103; |
7 | 9 |
|
8 | | -function getLastDigit() { |
| 10 | + |
| 11 | +function getLastDigit(num) { |
9 | 12 | return num.toString().slice(-1); |
10 | 13 | } |
11 | 14 |
|
| 15 | + |
12 | 16 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 17 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | 18 | console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 19 | +console.log(`The last digit of 7247 is ${getLastDigit(7274)}`); |
| 20 | + |
15 | 21 |
|
16 | 22 | // Now run the code and compare the output to your prediction |
17 | | -// =============> write the output here |
| 23 | +/* ===========> function getLastDigit() { |
| 24 | +return num.toString().slice(-1); |
| 25 | + */ |
18 | 26 | // Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
| 27 | +// =============> this is because the /1 is not defined and not valid in the system of javaScript languague, so it throws an error. Morever because the parameter for the function is not defined, the function takes the global variable scope to run the code inside it. So obviously, we need to put down a parameter which is num to have the function work for any number other than the global variable scope. |
20 | 28 | // Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
| 29 | +/* ============> function getLastDigit(num) { |
| 30 | +return num.toString().slice(-1); |
| 31 | +} |
| 32 | +*/ |
| 33 | + |
22 | 34 |
|
23 | 35 | // This program should tell the user the last digit of each number. |
24 | 36 | // Explain why getLastDigit is not working properly - correct the problem |
| 37 | + |
| 38 | + |
| 39 | + |
0 commit comments