-2

Using the following code how can I access a from inside log2?

   (function() {
     function log() {
       var a = "string";
     }
     log()

     function log2() {
       console.log(log.a);
     }

     console.log(log);
     log2();
   })()
Tom O.
  • 5,730
  • 2
  • 21
  • 35

1 Answers1

1

Variables declared with the var keyword in JavaScript are function-scoped. This means that they cannot be accessed from outside the function they were declared in without returning them. The solution is to declare the variable within your outer immediately-invoked function, which will enclose the variable and make it available to the two inner functions:

(function() {
  var a;

  function inner1 () {
    a = 'string';
  }

  function inner2 () {
    console.log(a);
  }

  inner1();
  inner2(); // => logs 'string'
})()

console.log(a); // => logs undefined, because a is enclosed
sbking
  • 7,630
  • 24
  • 33