What is Scope?
Scope determines the accessibility (Visibility) of your variables. It defines where you can see, use, or change a specific variable in your code.
There are three types of scope in JavaScript.They are
- Global Scope
- Block Scope
- Function Scope
Global Scope:
- Variables that are declared outside of any function.
- These Global scope variables can be accessed from anywhere.
<script>
let a=10;
const b=20;
var c=30;
function add(){
console.log(a);
console.log(a+b+c);
}
add();
</script>
Output:
10
60
Here, the variables a,b and c are accessible inside add() because functions can access global variables.
Block Scope:
- Before ES6, JavaScript variables could only have Global Scope or Function Scope.
- ES6 introduced two important new JavaScript keywords: let and const.
- These two keywords provide Block Scope in JavaScript.
Variables declared with let and const inside a block ({}) are accessible only within that block.
<script>
{
let d=10;
const e=25;
console.log(d+e);
}
console.log(d+e);
</script>
Output:
35
Uncaught ReferenceError: d is not defined
Why this Uncaught ReferenceError means variables declared with let and const are block scope. So we can't access them outside the block.
Function Scope:
Variables declared with var, let, or const inside a function are only accessible within that function.
<script>
function function_scope(){
let name="Raksha";
var num=25;
const pi=3.14;
console.log(name);
console.log(num);
}
function_scope();
console.log(num);
console.log(pi);
</script>
Output:
Raksha
25
Uncaught ReferenceError
Why this Uncaught ReferenceError means variables declared inside a function have function scope. So we can't use them outside of the function.
Top comments (0)