Skip to content

Commit 09df5e9

Browse files
committed
Predict what the sum function will output, explain how the code works, and fix the code.
1 parent f4b2ba4 commit 09df5e9

File tree

1 file changed

+33
-0
lines changed
  • Sprint-2/2-mandatory-debug

1 file changed

+33
-0
lines changed

Sprint-2/2-mandatory-debug/1.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
// Predict and explain first...
22
// =============> write your prediction here
3+
// Answer
4+
// I predict that calling sum(10, 32) will return `undefined`.
5+
// This is because the `return` statement has a semicolon immediately after it,
6+
// so JavaScript interprets it as `return;` which evaluate to "undefined" when the function is called
7+
// The expression `a + b` on the next line will never be executed.
8+
// Therefore, any console.log using sum(10, 32) will display `undefined` in the output.
9+
310

411
function sum(a, b) {
512
return;
@@ -9,5 +16,31 @@ function sum(a, b) {
916
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
1017

1118
// =============> write your explanation here
19+
// Explanation
20+
// function sum(a, b) {
21+
// This declares a function named sum that takes two parameters: a and b.
22+
23+
// return;
24+
// The return statement is immediately followed by a semicolon.
25+
// This causes the function to exit immediately.
26+
// Since nothing is returned explicitly, JavaScript returns undefined by default.
27+
28+
// a + b;
29+
// This line never executes because the function has already exited at the `return;` line.
30+
31+
// console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
32+
// In this expression, sum(10, 32) is called.
33+
// Because the function returns undefined, the template literal becomes: "The sum of 10 and 32 is undefined"
34+
// That string is printed to the console.
35+
1236
// Finally, correct the code to fix the problem
37+
// I will fix the error by placing the expression a + b on the same line as the return statement.
38+
// Optionally, I can use parentheses around the expression, but this is not required.
39+
1340
// =============> write your new code here
41+
42+
function sum(a, b) {
43+
return (a + b);
44+
}
45+
46+
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);

0 commit comments

Comments
 (0)