Stav Alfi
Stav Alfi

Reputation: 13953

Why a free identifier is found even thought he wasn't defined in a function?

function f(){
    function f1(){
       console.log(a)
    } 
    var a =3;  
    console.log(this.hasOwnProperty("a"))
    console.log(f.hasOwnProperty("a"))
    f1();
}
f()

Output:

false
false
3

If JS has a lexical scope then the scope of f1 is defined when f1 was defined which at that time, a wasn't defined. Also a is not a property of an object, then my question is why f1 finds the identifier a?

Upvotes: 0

Views: 29

Answers (1)

Isaac
Isaac

Reputation: 12894

function f(){
  function f1(){
   console.log(a)
  } 
  var a =3;  
  console.log(this.hasOwnProperty("a"))
  console.log(f.hasOwnProperty("a"))
  f1();
}
f() 

The snippet above, will first execute function f and steps are as below:

  1. declare variable a //a is undefined at this step (aka hoisting)
  2. initialize the function f1 //not invoking at all
  3. assign 3 to variable a
  4. logging both statement to be false
  5. Invoking function f1
  6. f1 trying to console.log(a), and variable a wasn't found within f1
  7. Perform lexical chain lookup, and trying to find variable a at function f
  8. Found it, print it, exit

The problem is not really with hoisting as pointed out by @CertainPerformance because what really happened is that, when f1 trying to perform a logging, it's simply perform a lexical chain lookup to find variable a at function f

Upvotes: 1

Related Questions