JavaScript Scope
Scope determines the visibility and lifetime of variables. JavaScript has function scope, block scope (with let and const), and global scope, influencing how variables are accessed.
Key Topics
Global Scope
Variables declared outside functions are global and accessible from anywhere in the code.
Function Scope
Variables declared with var inside a function are scoped to that function.
function test() {
var x = 10;
}
// console.log(x); // ReferenceError: x is not defined
Output
> ReferenceError
Explanation: x is only accessible inside the test function.
Block Scope
Variables declared with let or const are scoped to the nearest block, like if statements or loops.
JavaScript Usage in DOM
Use proper scoping to avoid variable name collisions and ensure that DOM manipulations are predictable and maintainable.
<!DOCTYPE html>
<html>
<head><title>Scope in DOM</title></head>
<body>
<h1>Scope Demo</h1>
<button onclick="run()">Run</button>
<p id="result"></p>
<script>
let message = "Hello";
function run() {
let message = "Hi";
document.getElementById("result").textContent = message; // "Hi", from block scope
}
</script>
</body>
</html>
Key Takeaways
- Global: Accessible everywhere.
- Function Scope: var variables visible only within the function.
- Block Scope: let/const restrict visibility to nearest block.
- DOM Integration: Proper scoping prevents naming conflicts and confusion.