Basic JavaScript - Understand String Immutability

Tell us what’s happening:
Another really seemingly dumb question- if you can do this:

let myStr = "Bob";
myStr = "Job";

then why do we write let/var/const before any of it if its possible to declare a variable without a keyword in front of it? I know the answer to this is really obvious but I also dont know the answer lol…

Your code so far

// Setup
let myStr = "Jello World";

// Only change code below this line
myStr[0] = "H"; // Change this line
// Only change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Understand String Immutability

Link to the challenge:

You technically can (though newer rules and feature make it much more difficult), but it causes a problem. If you initialise a variable (
without a variable keyword, it will automatically be attached to the global object. That new variable will quite happily override any other variables with the same name, either ones you declared or ones already present, with no warning

This is due to how JS was originally designed (was a very small language for scripting tiny things in browsers), and the way it works can’t be changed now

1 Like

That makes sense- thanks so much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.