39

I'm totally cool with this JSLint error. How can I tolerate it? Is there a flag or checkbox for it?

You get it when you do stuff like:

v && arr.push(v);

as opposed to:

if (v) {
    arr.push(v);
}

Both do the same exact thing. If you put:

window.test = function(v) {
    'use strict';
    var arr = [];
    if (v) {
        arr.push(v);
    }
    return arr;
};

into the minifier it minifies down to this anyway:

window.test=function(a){var b=[];a&&b.push(a);return b};
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
ryanve
  • 50,076
  • 30
  • 102
  • 137

4 Answers4

76

I don't think JSLint has an option to turn that off.

JSHint (a fork with more options) has an option for it, though: The expr option, documented as "if ExpressionStatement should be allowed as Programs".

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
37

You can add the following line to ignore that warning:

/*jshint -W030 */

You can read more about it here.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
ReedD
  • 997
  • 7
  • 6
11

People who are looking how to suppress it when using ESLint. You can ingnore it by writing the following comment just above the line no-unused-expressions

// eslint-disable-next-line no-unused-expressions

You can also suppress the warning for the entire file by placing the following comment at the very top of the file

/* eslint-disable no-unused-expressions */
Shivam
  • 3,091
  • 4
  • 30
  • 45
  • 1
    I recommend you to also provide the link of the documentation of this specific rule [no-unused-expressions](https://eslint.org/docs/rules/no-unused-expressions#top) – johannchopin Apr 08 '20 at 14:41
9

There's no option for this in JSLint. You can circumvent it using:

var dummy = v && arr.push(v);

NB: dummy evaluates to true after that.

Another workaround could be:

function expression(statement) { 
 'use strict';
 return statement; 
}
expression(v && arr.push);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 6
    It'll work but it's silly. The minifier will actually sort that out and but for readability it'd be better to just use the `if` statement than that IMO. – ryanve Mar 02 '12 at 13:50
  • That's true. But you asked for a way to tolerate is. Added another workaround. It's like Crockford said somewhere: *jsLint is designed to be a pain in the ass for programmers* ;~) – KooiInc Mar 02 '12 at 13:54
  • WRONG the wonderful && hack does not work in jsLint... maybe depends on version... – faebster Feb 12 '16 at 16:23