JavaScript Scope
Scope is the set of rules that determines where and how a variable can be looked up in your code. Think of it as a series of security clearances dictating who has access to what data.
Global Scope
Any variable declared completely outside of a function or block resides in the Global Scope. These variables are available everywhere in your JavaScript program. While convenient, overusing the global scope is dangerous because any script on the page can alter these variables, leading to bugs known as "global namespace pollution".
Local / Function Scope
Variables declared inside a function are local to that function. They are created every time the function is called and destroyed when the function finishes execution. The outside world cannot peek inside a function to see its local variables.
Block Scope (let & const)
Before ES6 (2015), JavaScript lacked Block Scope. Blocks are code contained within { } (like in if statements or for loops). Today, by using let or const, variables are strictly confined to the block they were declared in. The old var keyword ignores blocks entirely!
Lexical Scope & Closures+
JavaScript uses "Lexical Scoping". This means functions are executed using the variable scope that was in effect when they were defined, not when they are invoked. If you nest a function inside another, the inner function has access to the outer function's variables. This creates a "Closure", an incredibly powerful pattern for data privacy and function factories in JS.
