skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. … 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();
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search