Search code examples
javascriptnode.jsanonymous-functionjslintstrict

Why I need to wrap the code in immediately invoked function expression?


1) Why I need to wrap the below mentioned code in (function(){})(); , otherwise it is throwing error during JS linting and 2) I will also receive error if placing "use strict"; above (function(){})(); what I thought is to put "use strict"; at the very first line of page.

Please let me know about the two behaviors.

My Working code -

(function(){
"use strict";

// Constructing constructor function
// whose purpose is to create new 
// Person Objects
var Person = function(name) {
    this.name = name || "TestUser";
    this.hobbies = [];
};

Person.prototype.setHobby = function(hobby) {
    this.hobbies.push(hobby);
};

Person.prototype.getHobbies = function() {
    return this.hobbies;
};


exports.Person = Person;

var peter = new Person('peter');
peter.setHobby('Gambling');
peter.setHobby('Street Fighting');
peter.setHobby('Smoking');

peter.getHobbies();
})();

Solution

  • Use

    /*jshint node: true */
    

    at the top of your file. Even removing the IIFE, it then will pass jshint with flying colors.

    I would not recommend jslint. You will spend the rest of your life fighting with it and tweaking your code to make it shut up.