-6

Below is a piece of code from Eloquent Javascript's chapter-Modules.

var dayName = (function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
})();

and this:

var dayName = function(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number]; 
};
Mayank
  • 1
  • 4
  • 2
    The first keeps the names array in a closure, the second creates the name array every time. The first may be more efficient as it doesn't create the array every time, but the difference in performance is likely negligible. The only "bad practice" is not enclosing the first function expression in brackets, which make it clear from the start that it's an immediately invoked function expression (IIFE). – RobG May 03 '16 at 06:56

2 Answers2

1

What's the difference between these 2 functions in javascript

First one returns a method which (when invoked) will return the name of the weekday.

Second one returns the name of the weekday itself while taking the index from the array.

Is one of these two a bad practice?

Answer to this may vary from context to context. You will need to consider if the array in these two methods are live (constantly updating) or static, or whether small or big (then it doesn't make much sense to create it every time), or frequency of use (if need to be invoked a lot of times, this array will be created so many times), etc.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

None is the bad practice. But 1st code snippet is the better way.In 1st code you have created a module kind of structure which behaves like a separate entity and can be reuse. It have all its functionality inside it.

Sudarshan Tanwar
  • 3,537
  • 3
  • 24
  • 39
  • I don't know why doing a module is a better way than doing it with one function for this case. If he plans to do more methods then this will be true, but for only one function I think that doing a module is an overkill. – dlopez May 03 '16 at 07:10
  • Not for this particular case but as a practice module structure is good practice. – Sudarshan Tanwar May 03 '16 at 07:46