Scopes and Closures
November 8, 2019 Leave a comment
Like in other programming languages, variable scope in JavaScript is not created by blocks, instead its created from functions.
Ex:
var x = 1;
if(x === 1) {
var y = 'one';
}
console.log(x);
console.log(y); // prints 'one' as the scope is not block based
For the most part, scopes in JS are created via functions
var x = 1;
function assignValue() {
if(x === 1) {
var y = 'one';
}
}
console.log(x);
console.log(y); // will throw runtime error
Note *** variables ‘x’ from outer scope can be used inside function but not vice versa as in case of ‘y’
Global variables in JS are evil especially from browser perspective because we load everything at once and we dont know if our global variable names are conflicting with others from different libraries. For this reason we put our logic in a function expression and invoke that function but again the problem could be same if some 3rd party library has same global function. Hence we go for IIFE – Immediately Invoked Function Expression
(function () {
var a = 10;
var b = 20;
console.log(a+b);
})();
With IIFEs global namespace is not polluted.
Without declaring and defining a variable, if we try to use it we get and error.
By declaring and without defining a variable we get ‘undefined’
If we declare a variable, we can do both read and write operations fine, but if dont declare a variable then we can do write operation alone (and not read operation)
var x;
x = 10; // write operation
console.log(x); // read operation
console.log(y); // leads to runtime error as we cannot read before declaring
z = 10; // is fine as we can write without declaring a variable
The Window Object
Whenever we declare a variable outside a function then that variable becomes global. All the global variables and functions are wrapped inside a GLOBAL/ROOT object. This global object name depends on which runtime we are using for running JS.
If its the browser then the Global Object name is ‘window’.
If its node, then its called ‘global’
Scopes can be hierarchical: Variables declared inside a function (INNER VARS) can access variables declared outside the function (OUTER VARS)
Recent Comments