I see some different opinions here, but most of them are more based on what you think is better or not, but i don't see the technical reasons on when to use one or another, but for sure there are technical restrictions or advantages in use one declaration formula or another. I'm really a beginner with javascript and I don't feel confident to advise on it, but I will propose a case in which storing a function in a variable is not functional.
In the code below, defining an Angular filter, if I define the function inside a variable, then I can't successfully call it from the filter method. Could anyone explain me the technical reason on this?
See the code (commented is not working):
angular
.module('loc8rApp')
.filter('formatDistance', formatDistance);
function formatDistance(){
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
var _isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/*
var formatDistance = function () {
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
*/
Thank you in advance!
return
statement, and it'll still work.