Nearby lessons
28 of 40π JavaScript Scope (Global vs Local)
π What is JavaScript Scope?
In JavaScript, scope determines the accessibility of variables. π― There are two main types of scope: global and local.
A variable's scope is defined by where it is declared. Understanding scopes helps avoid bugs and write cleaner, more efficient code.
π Global Scope
Variables declared outside any function are in the global scope. They can be accessed and modified from anywhere in the code.
This is useful for values shared across multiple functions.
Code Example
π Local Scope
Variables declared inside a function are in the local scope. They are only accessible within that function.
This helps prevent unwanted interference from other parts of the code.
Code Example
π Function Access to Global Variable
Functions can access and use global variables. But modifying them directly can lead to unpredictable behavior in large applications.
Code Example
π Global Variable Not Accessible Inside Block Without var/let
Using a variable inside a block without declaring it with var, let, or const makes it global (not recommended).
Always use let or const to keep the variable local to that block.
Code Example
π Same Variable Name in Global and Local
If a local variable has the same name as a global one, the local variable takes precedence inside the function.
This is called variable shadowing.