|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | | -// =============> Write your prediction here |
| 4 | +// Write your prediction here |
| 5 | +// I think the output will be 'The last digit of 42 is 2', 'The last digit of 105 is 5', and 'The last digit of 806 is 6'. |
| 6 | +// I think this will happen because the getLastDigit function is supposed to take a number, convert it to a string, and |
| 7 | +// then return the last charecter of that string, which should be the last digit. |
5 | 8 |
|
6 | | -const num = 103; |
| 9 | +//const num = 103; |
7 | 10 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
| 11 | +//function getLastDigit() { |
| 12 | +// return num.toString().slice(-1); |
| 13 | +//} |
| 14 | + |
| 15 | +//console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 16 | +//console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 17 | +//console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 18 | + |
| 19 | +// Now run the code and compare the output to your prediction |
| 20 | +// Write the output here |
| 21 | +// The output is: |
| 22 | +// The last digit of 42 is 3 |
| 23 | +// The last digit of 105 is 3 |
| 24 | +// The last digit of 806 is 3 |
| 25 | + |
| 26 | +// Explain why the output is the way it is |
| 27 | +// write your explanation here |
| 28 | +// The output is 3 for all numbers because the function getLastDigit is not taking any parameters. It always uses the |
| 29 | +// global variable `num` which is set to 103. So it always returns the last digit of 103, which is 3. |
| 30 | + |
| 31 | +// Finally, correct the code to fix the problem |
| 32 | +// Write your new code here |
| 33 | + |
| 34 | +function getLastDigit(number) { |
| 35 | + return number.toString().slice(-1); |
10 | 36 | } |
11 | 37 |
|
12 | 38 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
13 | 39 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
14 | 40 | console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
15 | 41 |
|
16 | | -// Now run the code and compare the output to your prediction |
17 | | -// =============> write the output here |
18 | | -// Explain why the output is the way it is |
19 | | -// =============> write your explanation here |
20 | | -// Finally, correct the code to fix the problem |
21 | | -// =============> write your new code here |
22 | 42 |
|
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 | +// The function did not accept a parameter. It was a fixed variable (num = 103), so it always returned the last digit of 103. |
0 commit comments