Jay Sky
Jay Sky

Reputation: 143

Why are closures safer than global variables in JavaScript?

I'm pretty new to programming and yet can't understand some basic concepts.

I was reading this article http://www.w3schools.com/js/js_function_closures.asp (I got redirected there from another w3schools page telling me to 'avoid global variables').

However, I can't really understand how do closures "beat" the globals.

From what I have seen and read, global variables are dangerous, because any script or user can modify them what could possibly ruin the code functionality.

Anyway- if we consider code from the link:

var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

And if we consider global variable:

var counter = 0;
function add(){
counter = counter+1;
return counter;
}

How is the first case less accessible by script than second? Doesn't it take in both cases one line of code to change the variable? The only thing that came on my mind is declaring closure in another function where it gets executed, so it becomes accessible only locally:

function exec(){

var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

console.log(add());
}

But I don't think this would do the job.

Upvotes: 2

Views: 207

Answers (2)

John Gibbons
John Gibbons

Reputation: 322

The thing you might be missing is that the first add function is immediately executed. This is indicated by the parenthesis which follow its declaration. eg:

var something = function(){}();

Because this immediate execution returns a function, the add variable now represents that returned function with the counter variable set to 0 (which was also included in the immediately executed function).

Because it was declared within a function, that counter variable is now only visible to that function, and thus is protected from being overwritten by any other counter variable declared later in the program.

The calls to add now run that interior function, using the counter variable that was declared within add, and can now no longer be manipulated by anything but that interior function.

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223023

In the first case, code outside the add function cannot touch the counter. They could separately create a counter variable, but it would be a different variable from the counter used by add, and wouldn't affect the operation of add.

In the second case, any code that touched the global counter would be able to affect add's operation.

Upvotes: 5

Related Questions