0

I know that the execution context of JavaScript is created when a function is called. But I don't understand example below. Example 1 and Example 2 are very similar.

However, these results are not the same.

I already referenced the links.You-Don't-Konw JS and Blog reference and related to stackoverflow question

Example 1

var value = "Hello";

function bar() {
  var value = "Bye";

  function foo() {
    return value;
  }

  console.log(foo());
}

bar(); // Bye

Example 2

var value = "Hello";

function foo() {
  return value;
}

function bar(func) {
  var value = "Bye";
  console.log(func());
}

bar(foo); // Hello

I expected both results example 1 and example 2 to be Bye. If the execution context of the JavaScript is created at the time of the function call, why are the two results different?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mins
  • 11
  • 2

2 Answers2

0

The closure depends upon where the function was created not where it was called. The function foo in example 2 have no access to the local variable value of function bar. So therefore due to closure the value returned from foo is value of global scope.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

The two values here are different; they're just named the same. You can think of them as value in the global scope, and value in the scope of bar. Like having identically named files in two different directories, they're not actually the same.

Simon Brahan
  • 2,016
  • 1
  • 14
  • 22