|
2 | 2 |
|
3 | 3 | // Why will an error occur when this program runs? |
4 | 4 | // =============> write your prediction here |
| 5 | +// I predict that there will be two errors in this code. |
| 6 | +// The first error will be that the const decimalNumber |
| 7 | +// has already been declared in the function parameter, |
| 8 | +// it cannot be declared twice, which will cause an error because |
| 9 | +// it is not allowed to redeclare a variable with the same name. |
| 10 | +// The 2nd error is that console.log(decimalNumber) is trying |
| 11 | +// to log a variable that is outside the function, which will cause |
| 12 | +// an error because it is not defined. |
5 | 13 |
|
6 | 14 | // Try playing computer with the example to work out what is going on |
7 | 15 |
|
8 | 16 | function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | 17 | const percentage = `${decimalNumber * 100}%`; |
11 | | - |
12 | | - return percentage; |
| 18 | + return percentage; |
13 | 19 | } |
14 | 20 |
|
15 | | -console.log(decimalNumber); |
| 21 | +console.log(convertToPercentage(0.1)); // This will log "10%" |
| 22 | +// console.log(decimalNumber); // This will cause an error because decimalNumber is not defined outside the function |
| 23 | + |
16 | 24 |
|
17 | 25 | // =============> write your explanation here |
| 26 | +// decimalNumber is already a parameter so it can't be declared again |
| 27 | +// with const inside the function. Also, variables declared inside a |
| 28 | +// function are not accessible outside the function (scope), so |
| 29 | +// console.log(decimalNumber) out the function would fail. |
| 30 | +// the fix is to remove the const declaration and to log the percentage |
| 31 | +// instead of decimalNumber, which is the variable that holds the result |
| 32 | +// of the calculation (convertToPercentage(0.5)). |
18 | 33 |
|
19 | 34 | // Finally, correct the code to fix the problem |
| 35 | + |
| 36 | + |
20 | 37 | // =============> write your new code here |
0 commit comments