What is the lexical scope in JavaScript?

Abinash Panda
2 min readDec 31, 2019
function foo() {
let a = 11;
let b = 22;
let cal = () => a+b
return cal;
}
let x = foo()
x() // 33
  • In the above code, we are returning ‘foo’ function definition there is also two variables a and b then we are calling ‘foo’ and assign to x.
  • If you console.dir(x) you can see a lot of things but you can also see there are a ‘scopes’ and inside you can find our value which we declared in foo.

console.dir(x)
cal()arguments: (...)caller: (...)length: 0name: "cal"__proto__: ƒ ()[[FunctionLocation]]: VM97:4[Scopes]]: Scopes[3]0: Closure (foo) {a: 11, b: 22}1: Script {x: ƒ}2: Global {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

Let’s try that again

function foo() {
a = 11;
b = 22;
let cal = () => a*a
return cal;
}
let x = foo()
x() // 121

But wait this time there is no b in the closure because we are not using b modern JavaScript engine optimize our code that's why unnecessary things don’t come along with it.

What if we have the same value inside our returned function definition?

like this:

function foo() {
a = 11;
b = 22;
let cal = () =>{ var x = 2 return a*a}
return cal;
}
let x = foo()
x() // 4
  • So it will check for the value inside its function memory if not then it will check it’s ‘scopes’(if available) if still it not found then it will bubble out to its parent function.

Thanks for reading.

--

--