I was trying to understand the lexical scoping. I gone through here and I found all examples are related to nested functions. Is lexical scope only related to nested functions and parent to child accessibility?
Are there any examples of lexical scoping in js other than nested functions and closures?
AND
Does function parameters also form lexical scoping? For example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: "Hello, Alice!"
greet("Bob"); // Output: "Hello, Bob!"
2
Lexical scoping applies to any blocks, not just blocks with nested functions.
function testfun() {
let a = 1;
{
let a = 2;
a++;
console.log(a); // 3
}
console.log(a); // 1
}
testfun();
Note that only variables declared with let
or const
are block-scoped. Variables declared with var
have function scope, so if you used var a
in the above example they would be the same variable in the same scope. Before ES6, we would have used an IIFE to implement similar scoping.
Function parameters are scoped as if they’re declared in the top-level block of the function.