|
2 | 2 |
|
3 | 3 | // Why will an error occur when this program runs? |
4 | 4 | // =============> write your prediction here |
| 5 | +//decimalNumber already exists as a parameter, so const decimalNumber is making |
| 6 | +//a new variable with the same name. There is also a problem where decimalNumber is being |
| 7 | +//assigned 0.5, which won't cause errors, but means that no matter what is passed to the function |
| 8 | +//decimalNumber will always be 0.5 |
5 | 9 |
|
6 | 10 | // Try playing computer with the example to work out what is going on |
7 | 11 |
|
8 | | -function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | | - const percentage = `${decimalNumber * 100}%`; |
| 12 | +//function convertToPercentage(decimalNumber) { |
| 13 | +// const percentage = `${decimalNumber * 100}%`; |
11 | 14 |
|
12 | | - return percentage; |
13 | | -} |
| 15 | +// return percentage; |
| 16 | +//} |
14 | 17 |
|
15 | | -console.log(decimalNumber); |
| 18 | +//convertToPercentage(0.6) |
| 19 | +//console.log(decimalNumber); |
16 | 20 |
|
17 | 21 | // =============> write your explanation here |
| 22 | +//SyntaxError: Identifier 'decimalNumber' has already been declared |
| 23 | +//prediction correct, decimalNumber already exists so causes error. Removing the line |
| 24 | +//shows another error |
| 25 | +//console.log(decimalNumber); |
| 26 | +// ^ |
| 27 | +//ReferenceError: decimalNumber is not defined |
| 28 | +//This is because of scope, decimalNumber is defined in the function, so it only has scope |
| 29 | +//in the function |
18 | 30 |
|
19 | 31 | // Finally, correct the code to fix the problem |
20 | 32 | // =============> write your new code here |
| 33 | + |
| 34 | +function convertToPercentage(decimalNumber) { |
| 35 | + const percentage = `${decimalNumber * 100}%`; |
| 36 | + |
| 37 | + return percentage; |
| 38 | +} |
| 39 | + |
| 40 | +let decimalNumber = 0.6; |
| 41 | +console.log(decimalNumber); |
| 42 | +console.log(convertToPercentage(decimalNumber)); |
0 commit comments