Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling context and lexical scoping

Tags:

javascript

Consider the following code.I’m not sure I completely understand lexical scoping, but, unless I’m misinterpreting everything I’ve been reading, an inner function can only reference outer variables that have been declared in the same context.

let a = 7;

function test() {
  return a;
}

function test2() {
  let a = 5;
  return test()
}

console.log(test2())

In other words, what matters is where such functions are born and NOT where they are called, which, in the case of my example code above, means that the variable “a” that test returns is not the same as the variable “a” declared and assigned the value of 5 in test2. It’s as if the “a” in test2 were foreign to test. Am I on the right track or is there something I’m missing?

like image 487
sebasgrammar Avatar asked Nov 23 '25 02:11

sebasgrammar


1 Answers

You seem to be on the right track.

Variables defined with let are local to whatever scope they are defined in, either the global scope or a function or a block inside a function. Code in a function or block can "see" variables declared within the same function or block, or variables in an outer scope such as an enclosing function or the global scope.

Your code has two distinct variables that happen to share the same name, a. Each let statement creates a brand new variable, at whatever scope the let statement appears in.

Because your two a variables are actually different and unrelated variables, we could rename them to have two different names, and the code will work the same. I will use global_a for one of them and test2_a for the other:

let global_a = 7;

function test() {
  return global_a; 
}

function test2() {
  let test2_a = 5;
  return test()
}

console.log(test2())

Now when you look at the code, you can see that test() only uses global_a. It doesn't even try to use test2_a. And in the test2() function, you can see that the test2_a variable is only assigned but never used!

Note that variables defined with var follow basically the same rules, except that inner blocks inside a function (like an if statement with curly braces) don't count. var only follows function scope and ignores blocks inside a function.

like image 167
Michael Geary Avatar answered Nov 25 '25 14:11

Michael Geary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!