Tell us what’s happening:
I would like to know what am I doing wrong here.
Your code so far
function myLocalScope() {
myVar ='use strict';
// Only change code below this line
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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.
You want to put the line of code @sitek94 mentions below the // Only change code below this line
You don’t want to change the line of code 'use strict'; because that string on it’s own has a specific meaning, it’s not just a string but says code in the function will be run in strict mode.
As mentioned, it’s worth pointing out that you change the 'use strict' directive, which is what normally would prevent you from creating an (unintended) global variable. I can’t really remember, but I believe the tests are always run in strict mode no matter what, but I might be wrong.
Here is the same code used in the browser:
No strict mode:
function myLocalScope() {
myVar = "test";
console.log('inside myLocalScope', myVar);
}
myLocalScope()
// inside myLocalScope test
window.myVar
// "test"
In strict mode:
function myLocalScope() {
'use strict'
myVar = "test";
console.log('inside myLocalScope', myVar);
}
myLocalScope()
// Uncaught ReferenceError: myVar is not defined
window.myVar
// undefined
Adding var myVar = 'use strict' doesn’t break your code, but it makes absolutely no sense. The point of 'use strict' is that the browser that reads your script will handle it with different (stricter) rules. This won’t happen in your code, though. Instead, you now have a pointless variable called myVar with a value of 'use strict'that you never use.
If you want the use strict rules to be applied to your functions, you’ll have to use it like this, without assigning it to a variable:
function myFunction(){
'use strict';
// function now does stuff according to strict rules
}