|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Why will an error occur when this program runs? |
| 4 | + |
4 | 5 | // =============> write your prediction here |
| 6 | +/** |
| 7 | + * Prediction: |
| 8 | + * An error will occur because the function parameter decimalNumber is being redeclared inside the function body using const. This creates a naming conflict - you can't have a parameter and a local variable with the same name. |
| 9 | + * Additionally, the console.log(decimalNumber) at the end will cause a ReferenceError because decimalNumber is not defined in the global scope - it's only defined within the function's scope. |
| 10 | + */ |
5 | 11 |
|
6 | 12 | // Try playing computer with the example to work out what is going on |
7 | 13 |
|
8 | | -function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | | - const percentage = `${decimalNumber * 100}%`; |
| 14 | +/** |
| 15 | + * Explanation |
| 16 | + * The code has two main problems: |
| 17 | + * Redeclaration error: The function parameter decimalNumber is being redeclared with const decimalNumber = 0.5 inside the function. In JavaScript, you cannot have a variable with the same name as a parameter in the same scope. |
| 18 | + * Scope error: The console.log(decimalNumber) at the end is trying to access a variable that only exists inside the function's scope. Variables declared inside functions are not accessible from the outside. |
| 19 | + * Logic error: Even if the scope issues were fixed, the function always returns "50%" regardless of the input because it overwrites the parameter with 0.5. |
| 20 | + */ |
11 | 21 |
|
12 | | - return percentage; |
13 | | -} |
14 | | - |
15 | | -console.log(decimalNumber); |
| 22 | +/** Original function: |
| 23 | + * |
| 24 | + * function convertToPercentage(decimalNumber) { |
| 25 | + * const decimalNumber = 0.5; |
| 26 | + * const percentage = `${decimalNumber * 100}%`; |
| 27 | + * |
| 28 | + * return percentage; |
| 29 | + * } |
| 30 | + * |
| 31 | + * console.log(decimalNumber); |
| 32 | + */ |
16 | 33 |
|
17 | 34 | // =============> write your explanation here |
18 | 35 |
|
19 | 36 | // Finally, correct the code to fix the problem |
20 | 37 | // =============> write your new code here |
| 38 | + |
| 39 | +function convertToPercentage(decimalNumber) { |
| 40 | + const percentage = `${decimalNumber * 100}%`; |
| 41 | + return percentage; |
| 42 | +} |
| 43 | + |
| 44 | +// Example usage: |
| 45 | +const decimalNumber = 0.5; |
| 46 | +console.log(convertToPercentage(decimalNumber)); // Output: "50%" |
| 47 | +console.log(convertToPercentage(0.80)); // Output: "80%" |
| 48 | + |
0 commit comments