In JavaScript, scope is the context in which code is executed.

So, let's look at what is the scope chain.

  function b() {
  console.log(x);
}

function a() {
  var x = 1;
  b();
}
var x = 5;
a();

What do you think this code will log?

It logs 5 because b() function lexically sitting in the global environment. It's attached the global object. It declared physically in the same environment that x is!

As you see it's not inside a function so, it's outer reference is global execution context.

  function a() {
  var x = 1;

  function b() {
    console.log(x);
  }
  b();
}
var x = 5;
a();

Let's look at the code above.

b() function is now inside a(). Then we can say b()'s reference is now a().

So, the code logs 1.


361 0 6