Fork me on GitHub

JSLint Error Explanations

JSLint will hurt your feelings. It's time to make them better!


Do not use 'new' for side effects

When do I get this error?

JSLint and JSHint will throw the "Do not use 'new' for side effects" error when they encounter a function invocation preceded by the new operator when not part of an assignment or comparison expression. JSHint will only issue this warning if the nonew option is set to true. In the following example we call the built-in Date function as a constructor but don't assign the returned instance to anything:

Why do I get this error?

This error is raised to highlight a a lack of convention. While the code is perfectly valid it contravenes best practice, and in the case of the example above it indicates completely pointless code.

By not assigning the return value of a constructor to something you will lose the reference to that instance. Generally, by constructing an instance you would want to keep that reference, whether to use again later or for "internal" use as part of a comparison. What's the point of constructing something you are going to throw away as soon as it's been created?

If you have a constructor function that performs work beyond simply setting up an instance, and you are calling that constructor just for these "side effects", consider reworking your code to allow you to call the function normally, without the new operator. In the following simple example the side effect of calling the constructor is the incrementation of a variable:

In the above example we create two instances of Person but only keep the reference to one. The second call is simply there for the side effect of incrementing the counter. This example could be reworked to increment the counter without calling the constructor:

In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W031. This means you can tell JSHint to not issue this warning with the /*jshint -W031 */ directive.


comments powered by Disqus