Reputation: 3
I tried to the opposite of what the exercise wanted. Instead of declaring a variable with var inside the function, I did it like this:
function myLocalScope() {
'use strict';
// Only change code below this line
myVar = "bebe"
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
I thought that since I used no var it would be global now. But it just says its not defined. Not even in the local scope. If I add var inside the function, then the function works.
Upvotes: 0
Views: 687
Reputation: 3028
Yes: Variable wont be accessible outside of function
if you are using use strict
unless you assign it global scope, in this case you have to either remove use strict
or prefix your variables with window.
like so: window.myVar
.
As window
is global, your variable will be available outside too.
function myLocalScope() {
'use strict';
// Only change code below this line
window.myVar = "bebe"
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', window.myVar);
Upvotes: 1
Reputation: 3345
Remove "use strict" and it should work . With strict mode, you can not use undeclared variables.
function myLocalScope() {
// Only change code below this line
myVar = "bebe"
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
Upvotes: 1