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?
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.
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).
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.
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.
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.
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.
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