Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable?
function() {
var myTest = "hi there";
( function( myTest ) {
myTest = "goodbye!";
} )();
console.log( myTest ); // myTest should still be "hi there" here, correct?
}
Naturally if I didn't declare myTest
inside the inner function it would create a closure and modify the original. I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope.
Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable?
function() {
var myTest = "hi there";
( function( myTest ) {
myTest = "goodbye!";
} )();
console.log( myTest ); // myTest should still be "hi there" here, correct?
}
Naturally if I didn't declare myTest
inside the inner function it would create a closure and modify the original. I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope.
2 Answers
Reset to default 12Yes, they effectively do. Each function creates a new scope, and the closest scope in which a requested variable is declared always takes precedence. No exceptions.
Just for the sake of pleteness. In these very similar examples, here is what happens with no parameter
var x = 'a';
( function( ) { //note that there is no parameter here
x = 'b';
alert('inner:'+x); //b
} )();
alert('outer:'+x); //b
and a var with the same name
var x = 'a';
( function( ) {
var x = 'b';
alert('inner:'+x); //b
} )();
alert('outer:'+x); //a