Skip to content

Commit 0642903

Browse files
committed
Fix syntax errors in convertToPercentage and square functions, and update predictions and explanations
1 parent 9bf321e commit 0642903

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,31 @@
33
// Why will an error occur when this program runs?
44
// =============> write your prediction here
55

6+
//Prediction: The program will fail with a SyntaxError because 'decimalNumber' is redeclared.
7+
68
// Try playing computer with the example to work out what is going on
79

810
function convertToPercentage(decimalNumber) {
9-
const decimalNumber = 0.5;
11+
//const decimalNumber = 0.5; <--- this line causes the syntaxError.
1012
const percentage = `${decimalNumber * 100}%`;
1113

1214
return percentage;
1315
}
1416

15-
console.log(decimalNumber);
17+
//console.log(decimalNumber); <--- this line causes the ReferenceError.
1618

1719
// =============> write your explanation here
20+
//1. Inside the function: Just like the previous example, the parameter `decimalNumber` acts as a local variable. Trying to redeclare it with `const decimalNumber = 0.5;` causes a crash.
21+
// Additionally, hardcoding 0.5 defeats the purpose of having a parameter at all.
22+
23+
// 2. Outside the function: The variable `decimalNumber` is "scoped" to the function. It doesn't exist in the outside world. When `console.log(decimalNumber)` runs globally, JavaScript doesn't know what it is,
24+
// causing a ReferenceError. You need to call the function and pass the number as an argument instead.
1825

1926
// Finally, correct the code to fix the problem
2027
// =============> write your new code here
28+
29+
function convertToPercentage(decimalNumber) {
30+
const percentage = `${decimalNumber * 100}%`;
31+
return percentage;
32+
}
33+
console.log(convertToPercentage(0.5));

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,22 @@
44
// this function should square any number but instead we're going to get an error
55

66
// =============> write your prediction of the error here
7-
7+
// Prediction: The code would likely return a syntax error because the parameter in the () is '3' and not 'num'.
88
function square(3) {
99
return num * num;
1010
}
1111

1212
// =============> write the error message here
13+
// SyntaxError: Unexpected number
1314

1415
// =============> explain this error message here
1516

17+
// A defined function in a () must be variable names, not values.
1618
// Finally, correct the code to fix the problem
1719

1820
// =============> write your new code here
1921

20-
22+
function square(num) {
23+
return num * num;
24+
}
25+
console.log(square(3));

0 commit comments

Comments
 (0)