1

In JavaScript, it is said that functions are executed using the scope that was in effect when the function was defined. It has nothing to do with the scope in effect when the function is called.

What exactly does it mean?

1

2 Answers 2

2

The output of the following is A because foo is defined in the scope of function a, so the variable data that it uses is the one that is also defined in the scope of function a.

It doesn't output B even though the function was called in the scope of function b where data = "B".

<div id="output"></div>
<script>
  var data = "global";

  function a() {
    var data = "A";
    function foo() {
       document.getElementById('output').innerHTML = data;
    }
    return foo;
  }

  function b() {
    var data = "B";
    var func = a();
    func();
  }

  b();
</script>
Sign up to request clarification or add additional context in comments.

Comments

0
// Global variables are on every scope chain
var global = 'global'

// Function variables are only on a function's scope chain
function bar() {
  var fn = 'fn';

  // foo called from here where fn is avaialble as a local variable
  foo(); // undefined

  return function() {
    alert(fn)
  }
}


function foo() {
  // foo can access global because it's on its scope chain
  alert(global);

  // Can't access fn because it's on bar's scope chain
  // so returns undefined
  alert(typeof fn);    
}

// the function returned by bar has access to fn
var f = bar(); // global

f(); // fn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.