tonitone120
tonitone120

Reputation: 2310

Is this true about functions accessing variables?

1

function test(params) {
    console.log(color);
}

let color = "red";

test();

2

function test(params) {
  console.log(color);
}

test();

let color = "red";

1 function seems to be able to 'see'/access color because the line which invokes the function can see color. When the line that invokes the function is above color (like in 2) the only way color is seen is if it is 'above' or inside the function some way.

Is it fair for me to deduce this rule:

FunctionA can access a (non-global) variable that exists outside functionA when it is seen by the line that invokes functionA?


Please don't comment linking to a big document about closures. I'm talking about a specific situation.

Upvotes: 2

Views: 66

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

FunctionA can only access a (non-global) variable that exists outside functionA when it is seen by the line that invokes functionA?

No. Counterexample:

const getTest = () => {
  function test(params) {
      console.log(color);
  }

  let color = "red";
  return test;
};

const test = getTest();
// Here, `color` cannot be seen
// but the function still runs fine
test();

Whether a variable can be seen at a particular point in code depends (for most situations worth caring about) the lexical position of the variable's definition in relation to the point where it's being used.

A variable can be seen if it's initialized (eg with let or const) in the same block, or in an ancestor block.

A variable cannot be seen if it's initialized (eg with let or const) in a block which is not the same or an ancestor block.

The call chain does not affect scope.

Upvotes: 1

Related Questions