|
2 | 2 |
|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
| 5 | +// I predict all three lines will say the last digit is 3, because getLastDigit |
| 6 | +// has no parameter and always uses the global num, which is 103. |
5 | 7 |
|
6 | | -const num = 103; |
7 | | - |
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
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)}`); |
| 8 | +// const num = 103; |
| 9 | +// |
| 10 | +// function getLastDigit() { |
| 11 | +// return num.toString().slice(-1); |
| 12 | +// } |
| 13 | +// |
| 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 | +// The last digit of 42 is 3 |
| 21 | +// The last digit of 105 is 3 |
| 22 | +// The last digit of 806 is 3 |
| 23 | + |
18 | 24 | // Explain why the output is the way it is |
19 | 25 | // =============> write your explanation here |
| 26 | +// getLastDigit is declared with no parameters, so the arguments 42, 105 and 806 |
| 27 | +// are ignored. Inside the function, num refers to the global constant 103. |
| 28 | +// 103.toString() is "103" and .slice(-1) takes the last character, "3", every time. |
| 29 | + |
20 | 30 | // Finally, correct the code to fix the problem |
21 | 31 | // =============> write your new code here |
| 32 | +// Give the function a parameter so it uses the number passed in, and remove the global num. |
| 33 | +function getLastDigit(num) { |
| 34 | + return num.toString().slice(-1); |
| 35 | +} |
| 36 | + |
| 37 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); // 2 |
| 38 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); // 5 |
| 39 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); // 6 |
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 | +// It ignored its input because it had no parameter. Adding num as a parameter means |
| 44 | +// each call works on the number it was given. |
0 commit comments