Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Access Local Variable with Same Name in Inner and Outer Scope

Given the following JavaScript:

var someFunction = function(id) {
  //do some stuff
  var modifyId = function(id) {
     //do some stuff
     outer.id = id; //is there any way to modify the id variable in the outer scope from here?
  }
}

How do you modify the id passed into the outer function scope from within the inner function scope?

like image 264
Chris Shouts Avatar asked Oct 22 '10 22:10

Chris Shouts


People also ask

How do you access global variable if there is a local variable with same name in JavaScript?

Global variables can be accessed and modified anywhere in the program. Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other. JavaScript does not allow block level scope inside { } brackets.

Can a function and a variable have the same name JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).

What will happen if you declare a variable in a function with same name as a global variable?

If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.

What will happen if you define a local variable which has same name as the global one verify your answer with a proper code example?

5. What happens if a local variable exists with the same name as the global variable you want to access? Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable.


2 Answers

Unfortunately you can't. By naming the parameter in the nested function id, you've shadowed the parameter in the outer function. Javascript contains no facility for accessing the shadowed name. The only option is to choose a different name for one of the variables.

like image 161
JaredPar Avatar answered Sep 19 '22 15:09

JaredPar


No, there isn't. From within a function, there's no way (something weird in Mozilla's code or ES5 aside) to refer to the scope as a context in any explicit way, and there's no way to climb up the lexical scope chain in any direct way.

Good question though.

like image 40
Pointy Avatar answered Sep 21 '22 15:09

Pointy