Today I will be giving a small intro on scoping in JS.
Scoping determines where variables and functions are accessible within your code. In JavaScript, the main types are:
1.Global scope — accessible anywhere
2.Function scope — accessible only within the function
3.Block scope — accessible only within {} blocks (like if, for, etc.), using let or const.Eg
var userName = "Ranjani";
let email = "ranju@gmail.com";
const age = 30;
function printValue() {
const place = "Chennai";
console.log("Inside Function");
console.log(userName); // Ranjani
console.log(email); //ranju@gmail.com
console.log(age); // 30
console.log(place);
}
printValue();
console.log("Outside Function");
console.log(userName); // Ranjani
console.log(email);//ranju@gmail.com
console.log(place);// place is undefined error
console.log(age);// 30
if (1 < 2) {
var a = "Ranjani";
let b = "Harish";
const c = "Ramavel";
}
console.log(a); //This will get printed because var is function scoped
console.log(b); //undefined
console.log(c); //undefined
In the above example:
userName , email and age are global scoped which means they can be accessed from anywhere in the code...i.e even from inside functions and blocks.
place is function scoped and cannot be accessed outside of the function.
a , b and c are block scoped,,,in this since a is of type var it can be accessed outside the block whereas b and c cannot be accessed.
The variable types var is block scoped which means it can be accessed and modified outside of the block.....this can cause confusions and tend to create errors in larger applications and hence should be very sparingly used. The other two can be used often and are the most commonly used ones in modern day programming.
That's all about scopes in JS. See you all in the next post!
Top comments (0)