Scope in JavaScript
Scope determines where a variable can be accessed and used in a JavaScript program.
What is Scope?
In JavaScript, scope defines the area of a program where a variable is accessible.
In simple words, scope tells us where a variable can be used.
Simple Definition
Scope is the visibility and accessibility of variables in a JavaScript program.
Scope decides where a variable can be accessed.
Types of Scope in JavaScript
1. Global Scope – Variable can be accessed from different parts of the program.
2. Function Scope – Variables declared inside a function are accessible inside that function.
3. Block Scope
– Variables declared using
let and const
are accessible inside their block.
Example 1: Global Scope
A variable declared outside a function has global scope and can be accessed inside a function.
let course = "JavaScript";
function showCourse() {
console.log(course);
}
showCourse();
JavaScript
Example 2: Function Scope
A variable declared inside a function can be accessed only inside that function.
function greet() {
let message = "Hello CIIT";
console.log(message);
}
greet();
Hello CIIT
Example 3: Block Scope
Variables declared with
let and const
are block-scoped.
if (true) {
let message = "Inside Block";
console.log(message);
}
Inside Block
Important Points
• Scope determines where a variable can be accessed.
• Variables declared outside functions can have global scope.
• Variables declared inside functions are available inside that function.
• let and const
follow block scope.
• Understanding scope helps prevent variable conflicts and unexpected behavior.
Summary
JavaScript scope defines where variables can be accessed. Global scope, function scope, and block scope help organize variables and control their visibility within a program.