|
1 | 1 | // Predict and explain first... |
2 | 2 | //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 | + ^ |
3 | 7 |
|
| 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`. |
4 | 27 | // call the function capitalise with a string input |
5 | 28 | // interpret the error message and figure out why an error is occurring |
6 | 29 |
|
7 | 30 | 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; |
10 | 33 | } |
11 | 34 | console.log(capitalise("hello")); |
12 | 35 | // str is used both as the function parameter (function capitalise(str)) and again in let str = ... |
0 commit comments