Javascript: scope and closure.

Standard

SCOPE:

Scope in a programming language controls the visibility and lifetimes of the variables and parameters. It also reduces naming collisions and provides automatic memory management.Most languages with C syntax have block scope. All variables defined in a block (a list of statements wrapped with curly braces) are not visible from outside of the block. The variables defined in a block can be released when execution of the block is finished. This is a good thing.

But in the case of Javascript language, it does not have block scope. Rather it has ‘function scope’.

It means that variables and parameters defined in a function are not visible from the outside of the function and a variable defined anywhere within a function is visible everywhere within the function.

code view:

var foo = function () {
var text1 = 'Hakuna Matata';
var text2 = "There are No Worries...";
var phrase = function () {
var mid = " --Swahili phrase means--";
text1 += mid + text2;
alert(global);//Hakuna Matata --Swahili phrase means--There are No Worries...
};
alert(global);//Hakuna Matata
phrase();
};
foo()

CLOSURE:
// create a maker function called greetings. It makes
// an object with welcome method and fname and greet private variables.
function greetings(fname,greet){
var fullname;
function welcome(greet){
fullname = 'Mr. '+ fname;
return 'Hello ' + fullname +' ->' + greet;
}
return welcome;
}
// making an instance of greetings.
var closureVar = greetings('Mushfiq');
alert(closureVar);
alert(closureVar('Good Evening'));

greetings method is defined as it is used without new prefix. Now, when we call greetings, it returns a new object containing welcome method whose reference is stored in closureVar variable. The welcome method still has privileged to access the greetings’s fname property and fullname variable even though greetings has already returned.welcome does not have access to a copy of  the parameter rather it has access to the parameters itself. This is possible because the welcome function has access to the context of greetings, in which it was created. This is CLOSURE.

Leave a comment