visit
Javascript fundamentals series Scopes, Hoisting, Closures
, we have gone deep into the Global Scope, first part of understanding scopes in Javascript. If you feel insecure, or want to take a quick look, I encourage you to read it first since we will be referring to global scope in this article.If you have ever written any piece of Javascript code, you probably already created local scope and exploited its benefits since it is almost impossible not to. I am saying that because if you ever create a variable inside a function, you just create a local scope, not a global one.Local Scope occurs when you create a variable inside a function. By doing that, the visibility and accessibility of the variable changes significantly.
var globalOne=16;
function testingScope(){
var localOne=12;
console.log(localOne); // 12
console.log(globalOne); // 16
}
testingScope() // 12 and 16
console.log(localOne); // Uncaught ReferenceError: localOne is not defined
console.log(globalOne); // 16
Since our variable globalOne is a global variable, we can access it anywhere. However, localOne variable is only accessible inside its scope. That’s why, if we call testingScope function, we can see both variables in the console.
In global scope, we can only access global variables, stored in window object. Unlike global variables, local variables are not accessible and are destroyed as soon as their scope ends. They stay in memory when their function, which they are created in, is called. That’s why they are only accessible during execution of their function. That is one of the key differences between global and local variables.If you use blocks, anything between {}, like if, switch, for, while, you can make use of block scope only if you define variable with let and const. It is a long sentence and I think I can explain better if I show it in the console.
if(‘anything returning true’){
let localVariable=12;
var otherLocalVariable=10;
console.log(localVariable); // 12
console.log(otherLocalVariable); // 10
}
console.log(localVariable) // Uncaught ReferenceError: localVariable is not defined
console.log(otherLocalVariable) // 10
Do you see their behavior? localVariable, defined with let, is only visible inside the block. otherLocalVariable, defined with var, is visible outside the block. Different behavior is because of the difference between var, let, const. Therefore, it is important to know the differences of them to understand block scope.
let simpleVariable=’global scope’
function testingVariableShadowing(){
simpleVariable=’local scope’; // reassignment
console.log(simpleVariable);
}
testingVariableShadowing(); // local scope
console.log(simpleVariable); // global scope
In global scope, simpleVariable’s value is still ‘global scope’ while when it is called in function scope, it changes to ‘local scope’.
If you would like to read more about Javascript Fundamentals, please take a look at the Learn Javascript Fundamentals Series.1.2.3.Happy Coding!!!