Here is when and how..
Problem to solve – find if an element exists in an array.
Bad code 1 – clutter global namespace
var names = ['Honda', 'BMW', 'Kia', 'Toyota'];
var findIfCarMakeIsInList = function(make)
{
return names.indexOf(make) > -1 ;
}
alert('Is Honda in list ->' + findIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + findIfCarMakeIsInList('Acura'));
|
Bad code 2 - slow because of initialization of local list every time method is call
var findIfCarMakeIsInList = function(make)
{
var names = ['Honda', 'BMW', 'Kia', 'Toyota'];
return names.indexOf(make) > -1 ;
}
alert('Is Honda in list ->' + findIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + findIfCarMakeIsInList('Acura'));
|
Closure helps us to
1. Avoid polluting global namespace
2. And get the benefit of global objects.
var FindIfCarMakeIsInList = function()
{
var names = ['Honda', 'BMW', 'Kia', 'Toyota']; // it will be initialized only once.
// return function reference so that if can be called.
return function(make)
{
return names.indexOf(make) > -1 ;
};
}();
alert('Is Honda in list ->' + FindIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + FindIfCarMakeIsInList('Acura'));
|
Thanks
Pradeep
Keep learning “JavaScript good part..”
No comments:
Post a Comment