Skip to content

Commit f4e38d3

Browse files
committed
Fix and explain redeclaration SyntaxError in convertToPercentage (1-key-errors/1.js)
1 parent 0fc35ed commit f4e38d3

File tree

1 file changed

+17
-0
lines changed
  • Sprint-2/1-key-errors

1 file changed

+17
-0
lines changed

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
// Why will an error occur when this program runs?
44
// =============> write your prediction here
5+
// I predict that this program will throw a error message - due to the variable decimalNumber being redeclared
56

67
// Try playing computer with the example to work out what is going on
78

@@ -15,6 +16,22 @@ function convertToPercentage(decimalNumber) {
1516
console.log(decimalNumber);
1617

1718
// =============> write your explanation here
19+
// Function covertToPercentage(decimalNumber) - it has a parameter named decimalNumber
20+
// Inside the function: const decimalNumber = 0.5; - this redeclares the same variable name that's already used for the parameter.
21+
// That causes a error: SyntaxError: Identifier 'decimalNumber' has already been declared - because you can't declare a const (or let)
22+
// with the same name as a parameter inside the same function scope.
23+
// JavaScript doesn't allow us to declare a new variable with the same name in the same scope, so it caused a error
1824

1925
// Finally, correct the code to fix the problem
2026
// =============> write your new code here
27+
function convertToPercentage(decimalNumber) {
28+
const percentage = `${decimalNumber * 100}%`;
29+
return percentage;
30+
}
31+
32+
console.log(convertToPercentage(0.5));
33+
34+
// Function decimalNumber = 0.5
35+
// It calculates 0.5 * 100 = 50
36+
// It returns "50%"
37+
// console logs 50%

0 commit comments

Comments
 (0)