|
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 | +// =============> write your prediction here: potential error, decimalNumber has already been declared, can't redaclare it again with a new variable in the same scope. |
| 5 | +//another error could be, console.log will try to access a local variable from the global scope. |
5 | 6 |
|
6 | 7 | // Try playing computer with the example to work out what is going on |
7 | 8 |
|
| 9 | +// step one: function convertToPercentage(decimalNumber) |
| 10 | +// function created with a parameter named (decimalNumber) |
| 11 | +// step two: const decimalNumber = 0.5; |
| 12 | +// error occurs because decimalNumber has been declared already in the fucntion, cannot declare another one with the same name , in the same scope. |
| 13 | +// program stops. |
| 14 | +// we have fixed the first error. Code runs again. |
| 15 | +// step three: const percentage = `${decimalNumber * 100}%`; |
| 16 | +// new variable called percentage created, then the JS code is inserted, where decimalNumber is multiplied by 100. |
| 17 | +// no errors here |
| 18 | +// step four: return percentage; |
| 19 | +// this line sends the value out of the function then stops the function. No errors so far. |
| 20 | +// Step five: console.log(decimalNumber); |
| 21 | +// error occurs again, because the value created in step four can't be stored in console.log, due to decimalNumber being a parameter inside the function. Outside the function |
| 22 | +// there is no variable named decimalNumber. |
| 23 | +// we have fixed console.log with (convertToPercentage(0.5), now the result will print properly. |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +//function convertToPercentage(decimalNumber) { |
| 28 | +// const decimalNumber = 0.5; |
| 29 | +// const percentage = `${decimalNumber * 100}%`; |
| 30 | + |
| 31 | +// return percentage; |
| 32 | +//} |
| 33 | + |
| 34 | +//console.log(decimalNumber); |
| 35 | + |
| 36 | +// =============> write your explanation here: my error predictions turned out to be true and i have played computer with js code to further illustrate my reasoning. |
| 37 | + |
| 38 | +// Finally, correct the code to fix the problem |
| 39 | +// =============> write your new code here: |
| 40 | + |
8 | 41 | function convertToPercentage(decimalNumber) { |
9 | | - const decimalNumber = 0.5; |
10 | 42 | const percentage = `${decimalNumber * 100}%`; |
11 | | - |
12 | 43 | return percentage; |
13 | 44 | } |
14 | 45 |
|
15 | | -console.log(decimalNumber); |
16 | | - |
17 | | -// =============> write your explanation here |
| 46 | +console.log(convertToPercentage(0.5)); |
18 | 47 |
|
19 | | -// Finally, correct the code to fix the problem |
20 | | -// =============> write your new code here |
|
0 commit comments