33// Why will an error occur when this program runs?
44// =============> write your prediction here
55
6+ // The code will throw a "SyntaxError: Identifier 'decimalNumber' has already been declared"
7+ // because the variable 'decimalNumber' is declared twice — once as a function parameter
8+ // and again with `const decimalNumber` inside the function.
9+ // Additionally, there will be a "ReferenceError: decimalNumber is not defined"
10+ // when trying to log it outside the function, since 'decimalNumber' only exists inside the function scope.
11+
612// Try playing computer with the example to work out what is going on
713
14+ /**
815function convertToPercentage(decimalNumber) {
916 const decimalNumber = 0.5;
1017 const percentage = `${decimalNumber * 100}%`;
@@ -13,8 +20,55 @@ function convertToPercentage(decimalNumber) {
1320}
1421
1522console.log(decimalNumber);
23+ */
24+
25+
26+
27+ // Predict and explain first...
28+
29+ // Why will an error occur when this program runs?
30+ // =============> write your prediction here
31+ // The code will throw a "SyntaxError: Identifier 'decimalNumber' has already been declared"
32+ // because the variable 'decimalNumber' is declared twice — once as a function parameter
33+ // and again with `const decimalNumber` inside the function.
34+ // Additionally, there will be a "ReferenceError: decimalNumber is not defined"
35+ // when trying to log it outside the function, since 'decimalNumber' only exists inside the function scope.
36+
37+ // Try playing computer with the example to work out what is going on
38+
39+ /** function convertToPercentage(decimalNumber) {
40+ const decimalNumber = 0.5;
41+ const percentage = `${decimalNumber * 100}%`;
42+ return percentage;
43+ }
44+
45+ console.log(decimalNumber);
46+ */
1647
1748// =============> write your explanation here
1849
50+ // The first error happens because 'decimalNumber' is redeclared inside the function
51+ // even though it’s already defined as a parameter. JavaScript does not allow
52+ // redeclaring parameters with `let` or `const`.
53+ // The second error happens because 'decimalNumber' is not defined in the global scope
54+ // — it only exists inside the function, so `console.log(decimalNumber)` cannot find it.
55+
1956// Finally, correct the code to fix the problem
2057// =============> write your new code here
58+
59+ /**
60+ function convertToPercentage(decimalNumber) {
61+ const percentage = `${decimalNumber * 100}%`;
62+ return percentage;
63+ }
64+
65+ console.log(convertToPercentage(0.5)); // Output: "50%"
66+ */
67+
68+ function convertToPercentage ( decimalNumber ) {
69+ const percentage = `${ decimalNumber * 100 } %` ;
70+ return percentage ;
71+ }
72+
73+ console . log ( convertToPercentage ( 0.5 ) ) ; // Output: "50%"
74+
0 commit comments