Hello. I’ve been confused about the variable topic. In the previous step, it was said that the variable that is not declared using let or const will automatically be a global variable. I tried to not use both of them but it resulted an error.
What’s making it even more confusing is that in the previous step, it was required not to use “var,” “let,” or “const,” but the code still ran successfully. Could someone please explain what’s happening?
The link for the previous step is here:
To avoid any misunderstanding, I intentionally didn’t use “const” in front of myVar variable so I could access the help button. Your code so far
function myLocalScope() {
// Only change code below this line
myVar = "Hello Beautiful!";
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Local Scope and Functions
I think what’s going on here is that the previous step was running in what some people refer to as “sloppy” mode, which allows you to create a variable without using var, let, or const. That’s why oopsGlobal = 5 worked even though you never officially declared it. This sloppy mode is actually the default for JS. But it’s not something you normally want to use because it allows for such bad behavior which lends itself to bugs.
So eventually they came up with “strict” mode for JS, which doesn’t allow some of these bad practices that sloppy mode allows. I’m assuming the JS for this step is running in strict mode and that’s why you are getting the reference error if you leave off the var, let, or const when defining myVar.
I’m also assuming that probably most of the JS lessons run in strict mode and they just turned it off for the previous step in order to demonstrate a concept. But really, you should always run your JS in strict mode and you should always use either let or const to declare your variables. So just take the previous lesson as an example of what you should never do