|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | // Why will an error occur when this program runs? |
4 | | -// =============> write your prediction here |
| 4 | +// I predict the code will generate 2 errors because one the variable decimalNumber is declared twice and two |
| 5 | +// the function is not called instead the variable decimalNumber is called and it can't be accessed because |
| 6 | +// it was declared locally as a parameter of the function |
5 | 7 |
|
6 | 8 | // Try playing computer with the example to work out what is going on |
7 | 9 |
|
8 | | -function convertToPercentage(decimalNumber) { |
| 10 | +/*function convertToPercentage(decimalNumber) { |
9 | 11 | const decimalNumber = 0.5; |
10 | 12 | const percentage = `${decimalNumber * 100}%`; |
11 | 13 |
|
12 | 14 | return percentage; |
13 | 15 | } |
14 | 16 |
|
15 | | -console.log(decimalNumber); |
| 17 | +console.log(decimalNumber);*/ |
16 | 18 |
|
17 | | -// =============> write your explanation here |
| 19 | +// After we run the code, it generated an error SyntaxError: Identifier 'decimalNumber' has already been declared |
| 20 | +// because we tried to declare decimalNumber again. After fixing this error again we got another error ReferenceError: decimalNumber is not defined |
| 21 | +// because the decimalNumber is locally scoped, javascript can't access it when the function is called |
| 22 | +// additionally the function was not called console.log(decimalNumber) this simply means print the value of decimalNumber |
18 | 23 |
|
19 | 24 | // Finally, correct the code to fix the problem |
20 | | -// =============> write your new code here |
| 25 | +// Here is the fixed code |
| 26 | +function convertToPercentage(decimalNumber) { |
| 27 | + const percentage = `${decimalNumber * 100}%`; |
| 28 | + |
| 29 | + return percentage; |
| 30 | +} |
| 31 | + |
| 32 | +console.log(convertToPercentage(0.5)); |
0 commit comments