-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0.js
More file actions
41 lines (28 loc) · 1.37 KB
/
0.js
File metadata and controls
41 lines (28 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Predict and explain first...
// I predict when this code runs, there will be a SyntaxError before the function executes.
// This is because the identifier 'str' has already been declared.
// call the function capitalise with a string input
// capitalise("hello");
// interpret the error message and figure out why an error is occurring
// Uncaught SyntaxError: Unexpected identifier 'string' - this is the error message.
// This error is occuring because the variable 'str' is being redeclared within the function, which is not allowed in JavaScript.
// The duplicate use if 'str' is causing the syntax error.
//function capitalise(str) {
//let str = `${str[0].toUpperCase()}${str.slice(1)}`;
//return str;
//}
// The issue is variable redeclaration.
// str is the function parameter.
// let str tries to create a new variable with the same name.
// JavaScript does not allow redeclaring a variable in the same scope.
// As a result, the code throws a SyntaxError when it encounters the second 'str' declaration.
// New code without the error:
// 0.js — fully fixed version
function capitalise(str) {
if (!str) return str; // handles empty string
return str[0].toUpperCase() + str.slice(1);
}
// Test it
console.log(capitalise("hello")); // should print "Hello"
console.log(capitalise("world")); // should print "World"
console.log(capitalise("")); // should print ""