I am new to JS and having a doubt with the below example. Please see the inline comments.
function outer() {
var x = 5;
console.log("outer",x); // Prints 5
console.log("-----------");
function inner() {
var x = 6;
console.log("inner",x); // Prints 6
console.log("outer",x); // Prints 6. How to print 5
console.log("-----------");
function _inner() {
var x = 7;
console.log("_inner",x); // Prints 7
console.log("inner",x); // Prints 7. How to print 6
console.log("outer",x); // Prints 7. How to print 5
console.log("-----------");
}
_inner();
}
inner();
}
outer();
By simply changing the names of "inner" variable to y and the "_inner" variable to z you will get your expected results.
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables — a scope chain. The closure has three scope chains: it has access to its own scope — variables defined between its curly brackets. it has access to the outer function's variables.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.
var comparatorFactory = function(data) { return function(a,b) { return data[a] - data[b]; } }; function some_object(...) { var so = this; so. data = {...}; var comparator = comparatorFactory(so. data); ...
May be this helps you. Assign your variables to your nested functions because therefore it is clear what varible should be used but they have to differ from each other in some way(name or via namespace):
function outer() {
var x = 5;
// or via namespace
// var out = { x : 5 };
console.log("outer",x); // 5
console.log("-----------");
function inner() {
inner.x = 6;
console.log("inner",inner.x); // 6
console.log("outer",x); // 5
console.log("-----------");
function _inner() {
_inner.x = 7;
console.log("_inner",_inner.x); // 7
console.log("inner",inner.x); // 6
console.log("outer",x); // 5
// namespace
// console.log("outer",out.x); // 5
console.log("-----------");
}
_inner();
}
inner();
}
outer();
In this example only two of three varibles are assign(not outer x) to functions because otherwise you could assess outer.x from outside outer function and assign it any value:
function outer(){
outer.x = 5;
...
}
// assign any value outside outer function
outer.x = 34;
But when a local variable is defined:
function outer(){
var x = 23;
}
Then there is no chance to assign this local variable(x) any value from outside outer function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With