Scope in JavaScript defines the accessibility of variables, objects, and functions.
JavaScript mainly provides two types of scope:
These scopes control the visibility and accessibility of variables.
Variables declared outside any function become global variables.
Global variables can be accessed and modified from anywhere in the program.
The variable userName is accessible inside both functions because it is global.
Variables declared inside a function without using var, let, or const become global variables.
After calling the function, userName becomes globally accessible.
Accessing a global variable before it is created will generate an error.
Always initialize variables before using them.
Variables declared inside a function using var, let, or const are local variables.
Local variables are accessible only within the function where they are declared.
This code generates an error because userName is local to createUserName().
Global and local variables can have the same name without affecting each other.
The local variable is used inside the function, while the global variable remains unchanged.
The function displays the local value first, while the global variable keeps its original value.
When a local variable has the same name as a global variable, the local variable hides the global variable inside that function.
This concept is called Variable Shadowing.
Modern JavaScript supports block scope using let and const.
This will generate an error because age exists only inside the block.
A student's roll number declared inside a function can only be used within that function.
101
| Scope Type | Accessibility |
|---|---|
| Global Scope | Accessible everywhere |
| Local Scope | Accessible only inside function |
| Block Scope | Accessible only inside block (let/const) |
Which variable can be accessed from anywhere in a JavaScript program?