But long story short, they both are not really something enlightening as you were always (or mostly) using them, so don’t expect to have your Eureka! moment after reading this but hopefully expect to understand and explain them when you need to.
Disclaimer: all below are meant to be a theory standpoint and not a technical view about how to can take advantages of scope and closure (or their risk) as we can have a separate article for that
Scope is basically my where-to find variables or functions (yes that simple) and it will state where my
var a = 10; exists and is available for usage. Scopes are created either by function or block scope.
A function declaration will create a new scope where variables & functions can be declared. For a function
test() I create a basket where variables will reside. If a
var x = 10; is executed within
function test() then x is available for the
Note that if not in ‘strict mode’ we were to declare a variable like
x = 10;within the scope of
test()then this will bubble until the global scope and get allocated and assigned there due to the missing
varkeyword. If on ‘strict mode’ then this will throw and exception
Block scope is basically a wrapper for execution lines enclosed by
var declarations are not affected by block scope as they behave as function scope, whereas
function respects block scope.
Due to this, sometimes closures can create memory leaks if not taken care or cleaning timeouts and intervals.
Scope is my ‘where to get things’ on my current execution context and we have two types of scope: function and block.
The example below shows the creation of a
MakeCounter utility that encloses the
count variable for each instance created by