|
1 | 1 | // Predict and explain first... |
2 | | - |
3 | 2 | // Why will an error occur when this program runs? |
4 | 3 | // =============> write your prediction here |
5 | | - |
| 4 | +// I think there will be an error as "decimalNumber" variable has already been declared as a parameter in |
| 5 | +// "convertToPercentage" function |
| 6 | +// |
6 | 7 | // Try playing computer with the example to work out what is going on |
7 | 8 |
|
8 | | -function convertToPercentage(decimalNumber) { |
| 9 | +/*function convertToPercentage(decimalNumber) { |
9 | 10 | const decimalNumber = 0.5; |
10 | 11 | const percentage = `${decimalNumber * 100}%`; |
11 | 12 |
|
12 | 13 | return percentage; |
13 | 14 | } |
14 | 15 |
|
15 | | -console.log(decimalNumber); |
| 16 | +console.log(decimalNumber); */ |
16 | 17 |
|
17 | 18 | // =============> write your explanation here |
| 19 | +// =============Explanation =============== |
| 20 | +// the "decimalNumber" variable is a local variable and can only be seen inside "convertToPercentage" function |
| 21 | +// therefore when called outside the function it triggers "ReferenceError" |
18 | 22 |
|
19 | 23 | // Finally, correct the code to fix the problem |
| 24 | +// =========correction========= |
| 25 | +// problem can be fixed by moving the variable declaration outside the function |
| 26 | +// and making it global |
| 27 | + |
20 | 28 | // =============> write your new code here |
| 29 | + |
| 30 | +const decimalNumber = 0.5; |
| 31 | +function convertToPercentage(decimalNumber) { |
| 32 | + const percentage = `${decimalNumber * 100}%`; |
| 33 | + |
| 34 | + return percentage; |
| 35 | +} |
| 36 | + |
| 37 | +console.log(decimalNumber); |
| 38 | +console.log(convertToPercentage(decimalNumber)); |
| 39 | + |
| 40 | + |
0 commit comments