|
1 | 1 | // Predict and explain first... |
| 2 | +// My prediction: Running this code will result in a SyntaxError because 'decimalNumber' is defined as a parameter in the function declaration, and then re-declared on line 2 using 'const'. In JavaScript, an existing parameter or variable cannot be re-declared in the same scope using 'const' or 'let'. Additionally, calling console.log(decimalNumber) on line 8 will trigger a ReferenceError because 'decimalNumber' is scoped locally to the function and cannot be accessed globally. |
2 | 3 |
|
3 | 4 | // Why will an error occur when this program runs? |
4 | 5 | // =============> write your prediction here |
| 6 | +// My prediction: A SyntaxError will occur because 'decimalNumber' is automatically declared as a local variable when passed as a function parameter. Declaring it again inside the function body using 'const decimalNumber = 0.5;' breaks JavaScript's re-declaration rules. |
5 | 7 |
|
6 | 8 | // Try playing computer with the example to work out what is going on |
7 | 9 |
|
8 | | -function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | | - const percentage = `${decimalNumber * 100}%`; |
| 10 | +// function convertToPercentage(decimalNumber) { |
| 11 | +// const decimalNumber = 0.5; |
| 12 | +// const percentage = `${decimalNumber * 100}%`; |
11 | 13 |
|
12 | | - return percentage; |
13 | | -} |
| 14 | +// return percentage; |
| 15 | +// } |
14 | 16 |
|
15 | | -console.log(decimalNumber); |
| 17 | +// console.log(decimalNumber); |
16 | 18 |
|
17 | 19 | // =============> write your explanation here |
| 20 | +// =============> Two errors occurred here: |
| 21 | +// 1. SyntaxError: 'decimalNumber' is automatically declared as a local variable when passed as a function parameter. Declaring it again inside the function body using 'const decimalNumber = 0.5;' breaks JavaScript's re-declaration rules. |
| 22 | +// 2. ReferenceError: I commented out the 'const decimalNumber = 0.5' and got a ReferenceError, this is because 'decimalNumber' only exists within the block scope of the convertToPercentage function. Trying to log console.log(decimalNumber) in the global scope fails because it is not defined out there. |
| 23 | +// Solution: Remove 'const decimalNumber = 0.5;' from inside the function body so the parameter can receive the arguments, and call console.log(convertToPercentage(0.7)) instead of logging the parameter directly. |
18 | 24 |
|
19 | 25 | // Finally, correct the code to fix the problem |
20 | 26 | // =============> write your new code here |
| 27 | +function convertToPercentage(decimalNumber) { |
| 28 | + const percentage = `${decimalNumber * 100}%`; |
| 29 | + |
| 30 | + return percentage; |
| 31 | +} |
| 32 | + |
| 33 | +console.log(convertToPercentage(0.7)); // output 70% |
| 34 | +console.log(convertToPercentage(0.5)); // output 50% |
0 commit comments