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.

Example02
⚑Code Cell
Loading Editor...
✏️ You can edit this code β€” click Run to refresh the preview.
Output

πŸ”’ 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.

Example03
⚑Code Cell
Loading Editor...
✏️ You can edit this code β€” click Run to refresh the preview.
Output

πŸ” Function Access to Global Variable

Functions can access and use global variables. But modifying them directly can lead to unpredictable behavior in large applications.

Example04
⚑Code Cell
Loading Editor...
✏️ You can edit this code β€” click Run to refresh the preview.
Output

πŸ›‘ 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.

Example05
⚑Code Cell
Loading Editor...
✏️ You can edit this code β€” click Run to refresh the preview.
Output

πŸ”„ 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.

Example06
⚑Code Cell
Loading Editor...
✏️ You can edit this code β€” click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3