TheFullResolution
TheFullResolution

Reputation: 1311

Self invoking function written with 'var name = " in the front - bad practice?

In my knockout.js project I wrote some self invoking functions like this:

var addMarkers = function () {
    ko.utils.arrayForEach(self.sectionList(), function (sectionItem) {
        ko.utils.arrayForEach(sectionItem.placeList(), function (placeItem) {
            placeItem.marker.addListener('click', function () {

                map.panTo(placeItem.marker.getPosition());
            });
        });
    });

}();

The function works without problems, however in JSLint the "var addMarkers" was highlighted as unused variable. That makes me wonder if I should the function like this, or just make anonymous because it is a better practice?:

function addMarkers (){ code to be executed };

Upvotes: 0

Views: 136

Answers (1)

Roy J
Roy J

Reputation: 43899

Assigning the result of a self-executing function is often useful. In particular, I like to define my main viewmodel this way, because

  1. I don't need a prototype for my viewmodel
  2. I'm not likely to need more than one instance of a viewmodel

The reason you would use a self-executing function is that you need a local scope for whatever you're doing, to isolate it from surrounding scope. The reason you would assign a variable from it is that you want it to return a value you will use later. In your example, neither of these is true.

Upvotes: 0

Related Questions