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
PREVIEW READY
Loading Editor...
Live Preview

πŸ”’ 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
PREVIEW READY
Loading Editor...
Live Preview

πŸ” 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
PREVIEW READY
Loading Editor...
Live Preview

πŸ›‘ 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
PREVIEW READY
Loading Editor...
Live Preview

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!JS - Events