Javascript doesn't by default have blocked scope variable like many programming languages. This means that the variable x like you declared above, is the same variable.
Variable declarations, wherever they occur, are processed before any code is executed. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
I would suggest to not use the same variable name in a nested function. It becomes hard to read and debug. Also do you really need to have nested function ?
function outer() {
var x = 5;
console.log("outer",x); // Prints 5
console.log("-----------");
inner(x);
}
function inner(x1) {
var x = 6;
console.log("inner",x); // Prints 6
console.log("outer",x1); // Prints 5
console.log("-----------");
_inner(x,x1);
}
function _inner(x1, x2) {
var x = 7;
console.log("_inner",x); // Prints 7
console.log("inner",x1); // Prints 6.
console.log("outer",x2); // Prints 5.
console.log("-----------");
}
outer();
Or you could use object declaring it like so
function outer() {
var x = {
outer: 5
};
console.log("outer",x,outer); // Prints 5
console.log("-----------");
function inner() {
x.inner = 6;
console.log("inner",x.outer); // Prints 6
console.log("outer",x.inner); // Prints 6. How to print 5
console.log("-----------");
function _inner() {
x._inner = 7;
console.log("_inner",x._inner); // Prints 7
console.log("inner",x.inner); // Prints 7. How to print 6
console.log("outer",x.outer); // Prints 7. How to print 5
console.log("-----------");
}
_inner();
}
inner();
}
outer();