I have the following code to access global variable a from the nested function dd. but i am only able to access a from abc. How can we access a=6 from dd function.
var a = 6;
function abc() {
var a = 10;
a += 1
console.log(a)
function dd() {
a += 1
console.log(a)
}
dd()
}
abc();
3
Answers
Don’t shadow variables. (i.e. rename the
a
defined insideabc
to use a different name).Do use a linter with a rule to test for shadowing.
Since the variable you are trying to access is a global (not best practise) and uses
var
(also not best practise) then you can (if the code in running in a<script>
element) access it withwindow.a
. Refactoring your code to avoid shadowing is a better bet though.… and if you really need this:
What’s taking place here is a concept about scope.
The variable a is declared in the global scope and initialised with the value of 6. Then you created a function named abc and then created another variable named a and gave it a value of 10.
This is not best practice and it’s not recommended because it can cause unintended behaviour. The variable with the value 6 can be accessed from anywhere then the variable with the value 10 can only be accessed from anywhere as long as it is within the function abc or any function which is inside it.