|
3 | 3 | // Predict the output of the following code: |
4 | 4 | // =============> Write your prediction here |
5 | 5 |
|
6 | | -const num = 103; |
| 6 | +// I think the program will print 3 every time. |
| 7 | +// Even though different numbers are passed into the function, |
| 8 | +// the function is using the variable 'num', which is 103. |
7 | 9 |
|
8 | | -function getLastDigit() { |
9 | | - return num.toString().slice(-1); |
10 | | -} |
11 | 10 |
|
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)}`); |
| 11 | +// function getLastDigit() { |
| 12 | +// return num.toString().slice(-1); |
| 13 | +// } |
| 14 | + |
| 15 | + |
| 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 |
| 25 | + |
18 | 26 | // Explain why the output is the way it is |
19 | 27 | // =============> write your explanation here |
| 28 | + |
| 29 | +// The function is not using the number that is passed into it. |
| 30 | +// Instead, it always uses the global variable 'num' |
| 31 | +// which is set to 103. |
| 32 | +// The last digit of 103 is 3 |
| 33 | +// so the function always returns 3. |
| 34 | + |
20 | 35 | // Finally, correct the code to fix the problem |
21 | 36 | // =============> write your new code here |
22 | 37 |
|
| 38 | +function getLastDigit(number) { |
| 39 | + return number.toString().slice(-1); |
| 40 | +} |
| 41 | + |
| 42 | +console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
| 43 | +console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
| 44 | +console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
| 45 | + |
| 46 | + |
23 | 47 | // This program should tell the user the last digit of each number. |
24 | 48 | // Explain why getLastDigit is not working properly - correct the problem |
| 49 | + |
| 50 | +// The function was not working properly because it did not use |
| 51 | +// the number that was passed into it. |
| 52 | +// Instead, it used the global variable 'num', |
| 53 | +// which was always 103. |
| 54 | +// That is why it always returned 3. |
| 55 | +// |
| 56 | +// To fix the problem, I added a parameter to the function |
| 57 | +// and used that parameter to calculate the last digit |
| 58 | + |
0 commit comments