|
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 | +// decimalNumber is defined within the function so it will not be recognised in console.log(decimalNumber); |
5 | 5 |
|
6 | 6 | // Try playing computer with the example to work out what is going on |
7 | 7 |
|
| 8 | + |
| 9 | + |
| 10 | + |
8 | 11 | function convertToPercentage(decimalNumber) { |
9 | 12 | const decimalNumber = 0.5; |
10 | 13 | const percentage = `${decimalNumber * 100}%`; |
11 | 14 |
|
12 | 15 | return percentage; |
13 | | -} |
| 16 | +``} |
14 | 17 |
|
15 | 18 | console.log(decimalNumber); |
16 | 19 |
|
17 | | -// =============> write your explanation here |
| 20 | + |
| 21 | +// this is a function to convert a decimal number to a percentage - function declared |
| 22 | +// the decimal number is declared as 0.5 |
| 23 | +// percentage is calculated by multiplying the decimal number by 100 and then adding the % symbol |
| 24 | +// the answer returned is named percentage and gives a number followed by % |
| 25 | +// the answer will be printed in console |
18 | 26 |
|
19 | 27 | // Finally, correct the code to fix the problem |
20 | | -// =============> write your new code here |
| 28 | +// the error was actually 'decimalNumber' has already been declared |
| 29 | +// this was because decimalNumber was declared inside the function convertToPercentage(decimalNumber) and |
| 30 | +// declared again within the function with the const statement |
| 31 | +// once const decimalNumber = 0.5; was moved outside the function this error was resolved |
| 32 | +// that way the global decimalNumber exists and the function can still accept it as an argument |
| 33 | + |
| 34 | + |
| 35 | +// const decimalNumber = 0.5; |
| 36 | +// function convertToPercentage(decimalNumber) { |
| 37 | +// const percentage = `${decimalNumber * 100}%`; |
| 38 | + |
| 39 | +// return percentage; |
| 40 | +} |
| 41 | + |
| 42 | +// console.log(decimalNumber); |
| 43 | + |
0 commit comments