22
33// Why will an error occur when this program runs?
44// =============> write your prediction here
5+ // Answer
6+ // An error will occur when the program runs because a variable cannot be redeclared.
7+ // The parameter decimalNumber is already a declared variable, so it cannot be redeclared again.
58
69// Try playing computer with the example to work out what is going on
710
8- function convertToPercentage ( decimalNumber ) {
9- const decimalNumber = 0.5 ;
10- const percentage = `${ decimalNumber * 100 } %` ;
11+ // function convertToPercentage(decimalNumber) {
12+ // const decimalNumber = 0.5;
13+ // const percentage = `${decimalNumber * 100}%`;
1114
12- return percentage ;
13- }
15+ // return percentage;
16+ // }
1417
15- console . log ( decimalNumber ) ;
18+ // console.log(decimalNumber);
1619
1720// =============> write your explanation here
21+ // Answer
22+ //function convertToPercentage(decimalNumber) {
23+ //const decimalNumber = 0.5;
24+ //const percentage = `${decimalNumber * 100}%`;
25+
26+ //return percentage;
27+ //}
28+
29+ // When the script starts, JavaScript defines the function convertToPercentage, but it doesn’t run it yet.
30+ // This means that nothing is executed inside the function; only the function itself is stored in memory.
31+
32+ // console.log(decimalNumber);
33+ // At this point, JavaScript looks for a variable called decimalNumber in the current scope (the global scope), but none exists.
34+ // We only declared decimalNumber as a parameter inside the function (which hasn’t been called yet).
35+ // Result: Because decimalNumber isn’t defined globally, JavaScript will throw an error
36+ // At this point, JavaScript looks for a variable called decimalNumber in the current scope (the global scope).
37+ // But none exists — we only declared decimalNumber as a parameter inside the function (which hasn’t been called yet).
38+ // Error message: "SyntaxError: Identifier 'decimalNumber' has already been declared"
1839
1940// Finally, correct the code to fix the problem
2041// =============> write your new code here
42+
43+ decimalNumber = 0.5 ;
44+ function convertToPercentage ( decimalNumber ) {
45+
46+ const percentage = `${ decimalNumber * 100 } %` ;
47+
48+ return percentage ;
49+ }
50+
51+ const ActualOutput = convertToPercentage ( 15 ) ;
52+ console . log ( ActualOutput ) ;
53+ console . log ( decimalNumber ) ;
0 commit comments