-2

x declared after fn function but returns its value. Why fn didn't return undefined?

function doWork(){

  let fn = function(){ return x; }
  let x = 2;

  return fn();

}

console.log(doWork()); // 2

4
  • Please read how scope works in js w3schools.com/js/js_scope.asp Commented Dec 19, 2017 at 19:54
  • 1
    Because fn() is called after x is assigned. Commented Dec 19, 2017 at 19:55
  • let creates variables in a scope. There’s no ordering within a scope, just a "temporal dead zone". If this didn't work, it would be super annoying. Commented Dec 19, 2017 at 19:56
  • 1
    stackoverflow.com/questions/37916940/… Commented Dec 19, 2017 at 19:56

1 Answer 1

1

Inside of your doWork() function, first you set up a function and assign it to fn -- This function is not invoked yet. You then define x as 2. After this definition you invoke fn() by calling return fn().

Because JavaScript works from top-to-bottom, x is defined at the time you reference fn(), so fn() is able to return x correctly.

This can be seen in the following:

function doWork() {
  let fn = function() {
    return x;
  }
  let x = 2;
  return fn();
}

console.log(doWork()); // 2

Sign up to request clarification or add additional context in comments.

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.