|
2 | 2 |
|
3 | 3 | // Why will an error occur when this program runs? |
4 | 4 | // =============> write your prediction here |
5 | | - |
| 5 | +// the problem is in line 10, because we can not use the "decimalNumber" twice, currently once we used as parameter and again as variable, |
| 6 | +// this will cause an error "SyntaxError: Identifier 'decimalNumber' has already been declared" |
6 | 7 | // Try playing computer with the example to work out what is going on |
7 | 8 |
|
8 | | -function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | | - const percentage = `${decimalNumber * 100}%`; |
| 9 | +// function convertToPercentage(decimalNumber) { |
| 10 | +// const decimalNumber = 0.5; |
| 11 | +// const percentage = `${decimalNumber * 100}%`; |
11 | 12 |
|
12 | | - return percentage; |
13 | | -} |
| 13 | +// return percentage; |
| 14 | +// } |
14 | 15 |
|
15 | | -console.log(decimalNumber); |
| 16 | +// console.log(decimalNumber); |
16 | 17 |
|
17 | 18 | // =============> write your explanation here |
18 | | - |
| 19 | +// by line 9 the computer we remember the name of the function and its parameter but still it doesn't do any thing. |
| 20 | +// by line 10 the computer will try to declare a new variable with the same name as the parameter of the function |
| 21 | +// and it will cause an error because we can not use the same name twice in the same scope. even if it accept it no matter what argument |
| 22 | +//we pass to the function it will always take the value of the variable that we declared inside the function. |
| 23 | +//line 11 the computer will try to calculate the percentage but it will not reach this line because of the error in line 10. |
| 24 | +// line 13 the computer will try to print the value of decimalNumber but it will not reach this line because of the error in line 10. but if reach |
| 25 | +// it will always print 0.5 no matter what argument we pass to the function. |
| 26 | +// in this case the error is "SyntaxError: Identifier 'decimalNumber' has already been declared" but if we fix it , |
| 27 | +//then then console will give us the decimal number that we pass to the function in percentage format. |
19 | 28 | // Finally, correct the code to fix the problem |
20 | 29 | // =============> write your new code here |
| 30 | +function convertToPercentage(decimalNumber) { |
| 31 | + |
| 32 | + const percentage = `${decimalNumber * 100}%`; |
| 33 | + |
| 34 | + return percentage; |
| 35 | +} |
| 36 | + |
| 37 | +console.log(convertToPercentage(.45)); |
0 commit comments