Skip to content

Commit 2a91f72

Browse files
committed
1.js committed
1 parent cb65503 commit 2a91f72

File tree

1 file changed

+34
-7
lines changed
  • Sprint-2/1-key-errors

1 file changed

+34
-7
lines changed

Sprint-2/1-key-errors/1.js

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,47 @@
11
// Predict and explain first...
22

33
// Why will an error occur when this program runs?
4+
45
// =============> write your prediction here
6+
/**
7+
* Prediction:
8+
* An error will occur because the function parameter decimalNumber is being redeclared inside the function body using const. This creates a naming conflict - you can't have a parameter and a local variable with the same name.
9+
* Additionally, the console.log(decimalNumber) at the end will cause a ReferenceError because decimalNumber is not defined in the global scope, it's only defined within the function's scope.
10+
*/
511

612
// Try playing computer with the example to work out what is going on
713

14+
/** Original function:
15+
*
16+
* function convertToPercentage(decimalNumber) {
17+
* const decimalNumber = 0.5;
18+
* const percentage = `${decimalNumber * 100}%`;
19+
*
20+
* return percentage;
21+
* }
22+
*
23+
* console.log(decimalNumber);
24+
*/
25+
26+
// =============> write your explanation here
27+
/**
28+
* Explanation
29+
* The code has two main problems:
30+
* Redeclaration error: The function parameter decimalNumber is being redeclared with const decimalNumber = 0.5 inside the function. In JavaScript, it not possible to have a variable with the same name as a parameter in the same scope.
31+
* Scope error: The console.log(decimalNumber) at the end is trying to access a variable that only exists inside the function's scope. Variables declared inside functions are not accessible from the outside.
32+
* Logic error: Even if the scope issues were fixed, the function always returns "50%" regardless of the input because it overwrites the parameter with 0.5.
33+
*/
34+
35+
// Finally, correct the code to fix the problem
36+
// =============> write your new code here
37+
838
function convertToPercentage(decimalNumber) {
9-
const decimalNumber = 0.5;
1039
const percentage = `${decimalNumber * 100}%`;
11-
1240
return percentage;
1341
}
1442

15-
console.log(decimalNumber);
16-
17-
// =============> write your explanation here
43+
// Example usage:
44+
const decimalNumber = 0.5;
45+
console.log(convertToPercentage(decimalNumber)); // Output: "50%"
46+
console.log(convertToPercentage(0.80)); // Output: "80%"
1847

19-
// Finally, correct the code to fix the problem
20-
// =============> write your new code here

0 commit comments

Comments
 (0)