-4

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();
David
  • 208,112
  • 36
  • 198
  • 279
user2779311
  • 1,688
  • 4
  • 23
  • 31
  • 4
    What makes you think that this should be possible? How would that variable be named? If you don't want to override the global `a`, choose a different name – Nico Haase Jun 12 '23 at 13:43
  • 6
    Maybe `window.a` if the "global" `a` really is global? Though I imagine the ideal solution would be to not shadow a needed variable in the first place. Use different names for different values. – David Jun 12 '23 at 13:44

3 Answers3

4

Don't shadow variables. (i.e. rename the a defined inside abc 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 with window.a. Refactoring your code to avoid shadowing is a better bet though.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • if dd has its own var a then can it access variable a from abc function. pl update – user2779311 Jun 12 '23 at 13:52
  • 1
    No. If you shadow `a` inside `dd` then you cannot access `a` from a wider scope that is not attached to the `window` object. **Don't shadow variables**. – Quentin Jun 12 '23 at 13:54
0

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.

-1

... and if you really need this:

var a = 6;
function abc(copy = a) {
  var a = 10;
  a += 1
  console.log(a)
  function dd() {
    copy += 1
    console.log(copy)
  }
  dd()
}
abc();
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231