0

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 };

TheFullResolution
  • 1,251
  • 1
  • 15
  • 26

1 Answers1

0

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.

Roy J
  • 42,522
  • 10
  • 78
  • 102