|
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 | +// Here the name decimalNumber in 'const decimalNumber' has already been used, so we will get a synthax Error for that line. |
5 | 5 |
|
6 | 6 | // Try playing computer with the example to work out what is going on |
7 | 7 |
|
8 | | -function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | | - const percentage = `${decimalNumber * 100}%`; |
| 8 | +// function convertToPercentage(decimalNumber) { |
| 9 | +// const decimalNumber = 0.5; |
| 10 | +// const percentage = `${decimalNumber * 100}%`; |
11 | 11 |
|
12 | | - return percentage; |
13 | | -} |
| 12 | +// return percentage; |
| 13 | +// } |
14 | 14 |
|
15 | | -console.log(decimalNumber); |
16 | | - |
17 | | -// =============> write your explanation here |
| 15 | +// console.log(decimalNumber); |
18 | 16 |
|
| 17 | +// JavaScript is read from top to bottom, so when the processor reads an error, the program will stop running and will get the error message. |
| 18 | +//The first error is on line 9 with the reuse of the variable declaration name of 'decimalNumber. |
| 19 | +//The second error is on line 15 where we are trying to call the variable 'decimalNumber',which is a local variable inside the function. We cannot access this variable outside of the function. We will need to call the whole function. |
19 | 20 | // Finally, correct the code to fix the problem |
20 | 21 | // =============> write your new code here |
| 22 | +function convertToPercentage(decimalNumber) { |
| 23 | + const percentage = `${(decimalNumber * 100).toFixed(2)}`; |
| 24 | + return percentage; |
| 25 | +} |
| 26 | + |
| 27 | + |
| 28 | +console.log(convertToPercentage(0.5)); |
| 29 | +console.log(convertToPercentage(0.1234)); |
| 30 | +console.log(convertToPercentage(1)); |
0 commit comments