Types of Scope
Global scope: variables accessible everywhere (avoid polluting global). Global scope is the outermost scope in JavaScript. Variables declared in global scope are accessible from anywhere in the code, including inside functions and blocks. However, overusing global variables can lead to naming conflicts, security issues, and harder-to-debug code. In browser environments, global variables become properties of the window object.
Function scope: `var` is function-scoped — available across the containing function. Function scope means that variables declared with `var` inside a function are only accessible within that function and any nested functions. This creates a boundary that prevents external code from accessing internal variables. Function scope is created whenever a function is declared or invoked.
Block scope: `let` and `const` are limited to the nearest `{}` block. Block scope was introduced with ES6 and applies to variables declared with `let` and `const`. A block is any code enclosed in curly braces, such as if statements, loops, or standalone blocks. Variables in block scope are only accessible within that block and any nested blocks.
Module scope: In ES6 modules, variables are scoped to the module. Module scope provides encapsulation similar to function scope but at the file level. Variables declared in a module are not accessible from other modules unless explicitly exported. This helps in building modular, maintainable applications.