Skip to content

Commit 5cc752a

Browse files
Add actual error output and deeper TDZ explanation
1 parent b76934a commit 5cc752a

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

  • Sprint-3/1-key-errors

‎Sprint-3/1-key-errors/0.js‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,35 @@
11
// Predict and explain first...
22
//I think this code will show a SyntaxError. The function has two variables named str in the same scope.
3+
// ACTUAL ERROR (running the original code with `node 0.js`):
4+
// C:\Users\EarthHarvestAdmin\CYF2026 LAMLA KAMANA\Module-JavaScript-Fundamentals\Sprint-3\1-key-errors\0.js:8
5+
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
6+
^
37

8+
//SyntaxError: Identifier 'str' has already been declared
9+
10+
// WHY IT IS ILLEGAL (DEEPER EXPLANATION):
11+
// 1. SCOPE COLLISION: The function parameter `str` and the variable `let str`
12+
// exist in the exact same function scope. In JavaScript, `let` and `const`
13+
// do NOT allow redeclaring an existing variable in the same scope.
14+
//
15+
// 2. TEMPORAL DEAD ZONE (TDZ): When the JavaScript engine parses this function,
16+
// it hoists the `let str` declaration to the top of the function scope.
17+
// However, unlike `var`, `let` variables remain in an uninitialized state
18+
// (the TDZ) until the exact line of declaration is executed.
19+
//
20+
// 3. FATAL PARSING ERROR: Because this is a SyntaxError (not a runtime error),
21+
// the JavaScript engine catches the illegal redeclaration during the
22+
// compilation/parsing phase, BEFORE any code executes. This is why the
23+
// `console.log` on line 12 never runs—the script never gets past the
24+
// parsing stage.
25+
//
26+
// FIX: use a different name for the new variable, e.g. `result`.
427
// call the function capitalise with a string input
528
// interpret the error message and figure out why an error is occurring
629

730
function capitalise(str) {
8-
let result = `${str[0].toUpperCase()}${str.slice(1)}`;
9-
return result;
31+
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
32+
return str;
1033
}
1134
console.log(capitalise("hello"));
1235
// str is used both as the function parameter (function capitalise(str)) and again in let str = ...

0 commit comments

Comments
 (0)