JavaScript Scope – Global and Local Variables
Subject: JavaScript
Scope in JavaScript defines where a variable is accessible or "visible" in your code. Understanding scope is essential for writing predictable and bug-free JavaScript programs.
What is Scope?
In JavaScript, scope refers to the context in which variables are declared and accessible. There are two main types:
- Global Scope
- Local Scope
Modern JavaScript also introduces block scope with let and const.
1. Global Scope
A variable declared outside any function or block is in the global scope and can be accessed anywhere in the code.
Example: Global Variable
Global variables are accessible throughout your code. Avoid overusing them to prevent conflicts and bugs.
2. Local Scope
A variable declared inside a function is a local variable. It is only accessible within that function.
Example: Local Variable
Local variables help avoid conflicts and keep code modular.
3. Block Scope with let and const
Variables declared with let or const inside curly braces {} (like in if, for, or while) are only available inside that block.
Example: Block Scope
vardoes not have block scope — it is hoisted to the function level. Useletandconstto ensure predictable, block-level scoping.
Key Takeaways
- Global variables are declared outside all functions and accessible everywhere.
- Local variables are declared inside functions and cannot be accessed outside.
- Use
letandconstfor block-level scoping. - Avoid unnecessary global variables to prevent name collisions.
- Understanding scope helps write cleaner, modular, and safer JavaScript code.