Scope: Scope generally means the visibility and accessibililty of variables in different parts of your code. Understanding of differnt types of scopes helps us write error free and clear code.
Global Scope:
Global scope means the variable is having its accessibility anywhere in the program, inside function or blocks etc. But sometimes it leads to naming conflicts.
e.g:
let global = "I'm a global variable";
function display(){
console.log(global);
}
display(); // "I'm a global variable"
In this example, global is declared in the global scope and can be accessed inside the display function.
Local Scope:
The variables are only accessible within a function not outside of it.
e.g:
function local(){
var local = "I'm a local scope variable";
if (true){
console.log(local);// Works here also inside of if block
}
}
Block Scope:
The variables are accessed within that block not outside of it.
if (true) {
let block = "I'm a block variable";
console.log(block);// Works here inside of the block only
}
console.log(block);//it will throw an error
Let's try to understand the difference between var, let and const based on Scopes
How to declare variables in JS?
We can declare variables in JS using var, let and const.
A variable is like a container used to store a value.
var is a function scoped variable which can be redeclared and reassigned.
e.g: console.log("Nikita Maharana");
var a = 25;
var a = 3;//can redeclare using var in js
a = 56;//reassigning is possible
console.log(a);
let is a block scoped variable which can be reassigned but cannot be redeclared.
e.g: let x = 9;
// let x = 5;// cannot redeclare
x = 78;//reassigning is also possible using let not re-declare
console.log(x);
const is a block scoped variable which cannot be redeclared or reassigned.
e.g: const y = 11;
// const y = 22; cannot re-declare
//y = 30;//re-assigning is not possible
console.log(y);
So, basically we can say...var is function scoped variable & let and const are block scoped variables.
ex1:
function fun(){
if(true){
var a = 55;
}
console.log(a);//inside the fxn it will work everywhere
}
fun();
ex2:
function fun(){
if(true){
var a = 55;let b = 34;const c = 34
}
console.log(a,b);//inside the fxn it will work everywhere b will not be printed
console.log(c);//c is block scoped it will not be printed
}
fun();
Top comments (0)