Wednesday, April 23, 2014

Why need Closure in JavaScript

Safe and faster
//Global
var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
var digit_name = function (n) {
 return names[n];
};
alert(digit_name(3)); // 'three'

//Problem: not safe. It is global variable, other code could change it


//Slow
var digit_name = function (n) { 
 var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; 
 return names[n];
};
alert(digit_name(3)); // 'three'
//Problem: Safe but slow. Names hide in function scope, but need to initialize every time


//Closure
var digit_name = (function () {
 var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
 return function (n) {
 return names[n];
 };
}());
alert(digit_name(3)); // 'three
//Safe and fast 

But why closure version code is faster?
http://stackoverflow.com/questions/6614572/javascript-performance-with-closure

No comments:

Post a Comment