The Complete JavaScript Guide - Scope
Ajay Thopate
CEHv12 || CyberSecurity || Penetration Testing || Frontend developer | HTML | Tailwind CSS | JavaScript | React JS
In JavaScript, there are two types of variable scopes:
let globalLet = "This is a global variable";
function fun() {
let localLet = "This is a local variable";
console.log(globalLet);
console.log(localLet);
}
fun();
output ---> //This is a global variable
// This is local varibale
let globalLet = "This is a global variable";
function fun() {
let localLet = "This is a local variable";
}
fun();
console.log(globalLet); // This is a global variable
console.log(localLet);
output ---> // This is global variable
We are still able to see the value of the global variable, but for local variable console.log throws an error. This is because now the console.log statements are present in global scope where they have access to global variables but cannot access the local variables.