Coder Social home page Coder Social logo

jslint-org / jslint Goto Github PK

View Code? Open in Web Editor NEW
3.6K 3.6K 457.0 37.39 MB

JSLint, The JavaScript Code Quality and Coverage Tool

Home Page: https://www.jslint.com

License: The Unlicense

HTML 6.20% JavaScript 82.10% Shell 11.47% Vim Script 0.22%
coverage-report javascript jslint zero-config zero-dependency

jslint's People

Contributors

douglascrockford avatar juliankniephoff avatar kaizhu256 avatar matkoniecz avatar puneetgopinath avatar unrealapex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jslint's Issues

Option to tolerate var-declaration in for-loops

First, thank you for your great validation tool.

Demo-JavaScript:

var test = function () {
    var letsHaveSomeFun = {};

    for (var entry in letsHaveSomeFun) {
        alert("do anything");
    }
};

If I try to validate this coding, I get following errors:

Problem at line 6 character 10: Move 'var' declarations to the top of the function.
for (var entry in letsHaveSomeFun) {
Problem at line 6 character 10: Stopping. (57% scanned).

Now I would need an option to skip this 2 errors.
Is there any chance to get them?

Thank you.
Martin

Extra check for type coercion using !

I fell in a common pitfall today and was wondering whether an extra check may be added in JSLint in this regard:

function onCreditBalanceUpdate(event){
  if (!event.balance){ // Bug: balance value 0 is ignored
    return;
  }
  // ...
}

JSLint warns against type coercion using == in a comparison, but not using ! in a test.

A similar issue occurs with falsy values '' and 0 when setting the default value of an optional argument with the common idiom:

function doSomething(a,b){
  a = a || 'Missing'; // Issue: '' should probably not be treated as 'Missing'
  b = b || 10; // issue: 0 should probably not be treated as missing
  // ...
}

I am interested in any suggestion for extra precautions to avoid these issues.

switch/case fall-through ignored

According to http://www.jslint.com/lint.html

JSLint expects that the statement before the next case or default is one of these: break, return, or throw.

However, the following passes JSLint without any errors:

var name, value;
switch (name) {
case "indent":
case "maxerr":
case "maxlen":
    value = parseInt(value, 10);
    break;
case "predef":
    value = value.split(",");
    break;
default:
    break;
}

(tested today on jslint.com; code sample adapted from JSLint Reporter)

assignment within `while`

when using couchdb there's a loop which pass through every record in the database, but it only works with the following code:

var row;
while (row = getRow()) {

  //print some results
  send(row.title);
  send(row.author);

}

but this returns the following error on jslint:

Expected a conditional expression and instead saw an assignment

The problem is that there's no other way to achieve the same result besides assign a value to row from within the while argument for example

//doesn't work
var row = getRow();
while (row) {
  . . .
}

// doesn't work too
var row;
while (getRow()) {
  row = getRow();
  . . .
}

Bellow you can see how the getRow() method works...

function getRow() {
    if (lastRow) {
        return null;
    }
    if (!gotRow) {
        gotRow = true;
        sendStart();
    } else {
        blowChunks();
    }
    var line = readline();
    var json = eval("(" + line + ")");
    if (json[0] == "list_end") {
        lastRow = true;
        return null;
    }
    if (json[0] != "list_row") {
        throw ["fatal", "list_error", "not a row '" + json[0] + "'"];
    }
    return json[1];
}

So In this case I am just curious about how to get rid of the warning doing it right way, because I couldn't achieve the same result with any alternative.

Assume Node.js option falsely assumes global `util`

/*jslint node: true */

var util = require("util");

This leads to the following errors:

Problem at line 3 character 5: Redefinition of 'util'.
var util = require("util");

Problem at line 3 character 10: Read only.
var util = require("util");

Presumably earlier versions of Node used a global util - however, that global does not exist anymore.

The Node changelog suggests this was changed in v0.3.0.

Script error thrown when using global hasOwnProperty

As a simple repro, consider the following:

JSLINT('var foo;hasOwnProperty.call(foo,"bar");');

It throws the error "Cannot read property 'hasOwnProperty' of undefined" at line 3552 and stops processing the input.

It looks to me like this could be fixed by modifying line 3477 from

            if (!variable) {

to

            if (typeof variable !== "object") {

missing 'use strict' on sloppy

After reading your article I could understand that it is be possible to use both sloppy and strict functions within the same file when using the 'use strict' pragma. however the following example still asking for the pragma even on the sloppy function.

(function () { 
    "use strict"; 
    // this function is strict... 
}());
(function () { 
    // but this function is sloppy... 
}());

When using sloppy: true it doesn't require the pragma at all even for strict functions.

Unintentional tolerance for `this` inside of non-constructor functions

In the source code you seem to be explicitly checking for the use of this inside of non-constructor functions:

    reservevar('this', function (x) {
        if (strict_mode && ((funct['(statement)'] &&
                funct['(name)'].charAt(0) > 'Z') || funct === global_funct)) {
            warn('strict', x);
        } else if (option.safe) {
            warn('adsafe_a', x);
        }
    });

The problem is that—due to recent changes, I assume—you never set funct['(statement)'] to any truthy value so this check never succeeds. Because of that, the example shown below passes the JSLint check.

(function () {
  "use strict";

  function say() {
    this.hello = 'world';
  }

  say();
}());

Just pointing out, since it seems to me that this is unintentional.

JSLint should have an option to tolerate missing blocks.

That is there should be an option to turn off required blocks.

I say this not because I wish to write unblocked code. I say this because I sometimes have to modify or take over code that someone else has written.

A typical workflow when working on someone else's (javascript) code is:
i) download the code
ii) run the test code, checking that all tests pass
iii) run lint

The aim is to to have code that passes all tests and is lint-free before making any changes. This means that if you get any warnings or errors after you have made an amendment, then you know the errors are your own.

If you are lucky the code is already lint-free, but if it is not the process of getting it lint free involves a combination of making corrections to the code and setting the lint options. For most lint warnings this is fine: normally there is either a straightforward code-correction or the a suitable lint option. Note also that often turning off a lint warning is a tactical decision: if you need to fix a bug quickly then you may want to defer fixing lint problems until after you have fixed the bug.

However there is a problem with code blocks - there is no lint option and the process of putting braces around code can be error-prone, especially with if statements with lots of else clauses. This makes lint difficult to use, since any newly introduced lint warnings are lost in the noise of the "Expected '{' and instead saw ..." warnings.

The upshot of this is that, when modifying someone else's code, the utility of JSLint is often much reduced, often to the point of being almost unusable.

'exports' missing in node.js predefined globals

Node.js according to CommonJS Modules 1.0 standard provides exports and require variables within js module (file).
Apart of that node.js introduces module variable (not CommonJS standard) through wich we can make exports any object we like e.g. module.exports = obj

JSLint used with node flag predefines module and require global variables but not exports, that seems incomplete.

White space significance in JSON validation

Edition 2011-07-04
Clear All Options

Input:
[[1],[2]]

Output:
Error:

Problem at line 1 character 10: Missing space between ',' and '['.

[[10925],[10926]]

JSON: bad.

one space more:

Input:
[[1], [2]]
Output:
JSON: good.

Object.create kills JSLint

When run on the "classic" code snippet

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

the current git version of JSLint fails with the message:

6454: InternalError: too much recursion

I'm calling it from JavaScript (i.e., invoking JSLINT from fulljslint.js directly) without an options object. The version dated 2011-01-09 is the last one I could find that works with this code. All later versions fail on this code, and apparently, on any function definition with a non-empty parameter list.

Strict whitespace and loop labels

/*jslint continue: true, white: true, maxerr: 50, indent: 4 */

function myFunc() {
    var i, j;

    myLoop:
    for (j = 0; j < 10; j = j + 1) {
        i = 100;
    }
}

Running this through JSLint causes the error:
Problem at line 6 character 5: Expected 'myLoop' at column 1, not column 5.

Now in this example, column 1 might be acceptable for the label, but JSLint always insists on column 1 for labels, even if the code it matches is many levels of indentation deep.

I'm not sure what the best formatting for labels is, since they're used so rarely, but I don't think it's column 1.

Unexpected space error

I use JSLint to check my jQuery scripts and if I check code like this using "The Good Parts", it only tells me jQuery isn't defined - which is fine:

jQuery('.selector')
  .removeAttr('style')
  .show();

Now if I define an action and use it this way:

var showOrHide = 'show';
jQuery('.selector')
  .removeAttr('style')
  [showOrHide]();

I get an additional error stating Unexpected space before '['.

The only way to get rid of this error is to format the script like this, which I think make it more unreadable:

var showOrHide = 'show';
jQuery('.selector')
  .removeAttr('style')[showOrHide]();

So my question is would it be possible to make the second example not produce an error?

Thanks :)

Option to tolerate non-dot object property notation

Hi Douglas!

Currently it's impossible to use Google Closure Compiler's advanced compilation mode along with JSLint, because Closure Compiler forces a convention to use obj['property'] notation when defining a property that is not used in the code itself (e.g. it's a library) and you don't want it renamed by the compiler.

It would be great to add "tolerate non-dot property notation" option to solve this issue.

Thanks!

mootools 1.2.5 and fulljslint.js

In Firefox 3.6, JSLINT() always fails if the mootools 1.2.5 script is loaded along with fulljslint.js.

I reduced the problematic code in mootools to a one-liner:

Function.prototype['create'] = function() { return function(){}; }

Here's a hackish patch:

Index: fulljslint.js
===================================================================
--- fulljslint.js   (revision 4108)
+++ fulljslint.js   (working copy)
@@ -1224,7 +1224,7 @@
         };
     }

-    if (typeof Object.create !== 'function') {
+    if (typeof Object.create !== 'function' || typeof Function.create === 'function') {
         Object.create = function (o) {
             F.prototype = o;
             return new F();

"comparing identical expressions" discourages using un-broken isNaN() substitute

Working from the notions here, https://gist.github.com/1086528 , isNaN() is problematic because it coerces its value to a number. The best way to explicitly identify something as having the value of NaN is to do a reflexive comparison, since NaN is the only value for which x==x returns false.

ie,

function betterIsNaN(x){
    return !(x===x);
}

Except, JSLint throws a warning when I use that:

62: WARNING: useless comparison; comparing identical expressions

It's not quite accurate, since the potential for NaN values in the comparison means that identical values could potentially result in a reflexive expression evaluating as false.

Can you look at removing this warning, since this seems a valid application of comparing identical expressions?

Report Unused Parameters

I think it would be helpful it JSLint reported when parameters are not used. For example,

function func(param) {}

should report "param" as an unused variable.

Syntax tree doesn't distinguish between variables and string literals

The generated tree doesn't distinguish between vars and string literals. I'm writing a utility that reconstructs function calls from the tree (a rudimentary static analyzer) and there is no way to distinguish what is a variable from a string literal. For example, the JS:

getValue(thisIsAVar);
getValue("This is a string literal.");

generates this tree:

[
{
    "value": "(",
    "arity": "infix",
    "first": {
        "value": "getValue"
    },
    "second": [
        {
            "value": "thisIsAVar"
        }
    ]
},
{
    "value": "(",
    "arity": "infix",
    "first": {
        "value": "getValue"
    },
    "second": [
        {
            "value": "This is a string literal."
        }
    ]
}
]

per-line options

other lint implementation normally supports per line options, such as pylint http://pypi.python.org/pypi/pylint

This feature is useful to selectively allow some exceptions for some lines.

it would be good if jslint would support per-line options (which only affect the current line where the per-line option is specified, or the next line if the current line does not have any code). After the line is processed, the per-line option is forgotten (as if it's never been set) for following lines in the file.

syntax wise, I propose something like:
//jslint-line sub:true, bitwise:false
or
/jslint-line sub:true, bitwise:false/

Switchable function_strict warning rule

Currently there's no way to switch off function_strict warning.

This is not at great as in some environments (like node) javascript file is really a module and is treated as separate sandbox/function and there is no risk associated with non function wrapped use of 'use strict'.

I think there should be an option to turn off that warning and have it turned off by default in node mode.

Preformance

jslint.html now reports running times. I see these results when analyzing jslint.js with the Good Parts options:

Chrome 10.0.648.204 3.388 seconds.
Firefox 4.0.1       1.227 seconds.
IE 10.0.1000.16394  0.6   seconds.
Opera 11.01         1.248 seco

Weird condition error for comparison with null and 'null'

Running JSLint Edition 2011-06-06 against the following code results in a Weird condition error:

function is(value,type) {
  if (value === null){
    return (type === null || type === 'null');
  }
  // ...
}

This is a simplified version of the actual function is(...) in lb.base.type.js which accepts either values or strings for the type argument (cf API documentation).

Would it be possible to disable this check when the 'type' option of JSLint is set? Or is there any other way to avoid this error?

browser predefined globals

why is 'window' not in predefined globals if browser option is true?

If its not a mistake, what do you recommend to use instead?

this ? document.window ?

and why?

Thanks!

Add support for multi line strings

JSlint stops when it finds a multiline string literal.

e.g.

var hello = "hello
world";

This will result in the message:

"Bad escapement. Unclosed string. Stopping, unable to continue."

Bug: wrong "expected '}' indentation" error

When JSLint eats this ad-hoc code snippet:

/*global g */
function f() {
    g(
        function () {
        }
    );
}

it reports an error:
Problem at line 5 character 9: Expected '}' to have an indentation at 5 instead at 9.

I think JSLint is wrong because the indentation is correct.

Other really minor issues about code comments in fulljslint.js (2010-12-10):

  • line 1: maybe it should be fulljslint.js, not jslint.js;
  • line 39-40: "They are all are optional" has too many 'are'.

Thank you for this great tool! :)

Please find a better home than Yahoo Groups for the JSLint community, it is really troubling to get access to the database.

Allow shebang/hashbang for programs

Hi I am writing a program that uses the following:

#!/usr/bin/env node
var start, end, middle;
...

but unfortunately I get the validation error every time because of the shebang line, so I have to go delete it, then validate again, and put it back :)

Is there any way to assume that somehow?
I am sure this is completely not javascript, but sometimes can make life easier?

Thanks

Does passfail work?

I noticed that regardless of whether I set passfail: true/false and set maxerr to be a # > 1, JSLint would always stop after the 1st error.

Commenting this line out seemed to work for me:
rogerhu@ac9e88a

unparam directive ignored

It appears recent versions of JSLint (2011-05-10, possibly earlier) started ignoring the unparam directive:

/*jslint unparam: true */
/*global $ */

var onClick = function (ev) {
    $(this).hide();
};

$("#foo").click(onClick);

To my surprise, JSLint now reports

"Unused variable: ev 6 'onClick'"

here.

As I recall, this wasn't the case when unparam was first introduced. (Though it's possible my test case is faulty?)

False logging of functions

JSLINT this -
parseInt("not_a_function", function () { });

The log will show a function named "not_a_function".

Indentation of var declarations

I like to indent var declarations for readability. Here's an example (with contrived data for the purposes of this issue):

var a, b,
  c = 1,
  x = 2 +
    3,
  foo = 234 +
    4;

In particular, if an initialised variable needs to wrap I indent further. However, JSLint (2011-06-22) reports errors in these cases, telling me in this example that I've indented the '3' and '4' two characters too far.

In the common use case, which the above is not, reducing the intentation of the wrapped code or bracketing the expression would make it less readable. Unwrapping would also be a poor solution.

Is JSLint behaving correctly by reporting these as errors? If so, how should I be writing these types of declarations? Thanks.

preferences are not read any more from /*jslint */ comment

since release 2011-08-06 on http://jslint.com/ ,
preferences included in the JS code in the form of
/*jslint browser: true, sloppy: true, newcap: true, nomen: true, maxerr: 500, indent: 4 */
document.write('foo');

are not taken into account, nor in the analysis, nor in the checked settings, nor in the settings summary string at the bottom of the page.

Parentheses ignored in do loops

JSLint ignores parentheses around immediate invocations in do loops. Here's a simple example:

var a;
while ((a = 0)) {
    a = 0;
}

do {
    a = 0;
} while ((a = 0));

JSLint accepts the while loop but throws an error on the do loop.

global directive disables indentation checking

I believe there may be a bug in the directive() function. On row 2424:

    option.white = true;

But the "white" option is never reset to whatever value it had, hence in function expected_at(), row 1277:

    if (!option.white && next_token.from !== at) {

The indentation checks are disabled forever after.

Incorrect handling of multi-line strings with back slash?

I know it's probably arguable and unclear about this Javascript syntax, eg.
var queryXML =
"

urn:Microsoft.Search.Response.Document.Document




" + startAt + "" + numberOfResults + "
true
true

";

But for readability purpose, I still hope JSLint can support this syntax not only because all major browsers such as IE, Firefox, Chrome/Safari support it, but it's clearer and better than other solutions such as string combinations, etc.

Ref: http://kazoolist.blogspot.com/2008/06/multi-line-strings-in-javascript.html

function is not defined

JSLint has an issue with locally scoped functions being defined after use.

I find doing so improves readability a lot, as it shoves the utility functions down so the main logic is upfront.

Example, the primary thing for this code to do is create a div with "Hello World":

(function () {
    createDiv("Hello World");

    function createDiv(text) {
        var elem = document.createElement('div');
        elem.appendChild(document.createTextNode(text));
        document.body.appendChild(elem);
    }
}());

It reads a lot better with the function defined after, but JSLint incorrectly assumes it is a global.

I understand that you may feel like this is a scope issue like var being defined upfront, but when there are a lot of internal functions (for example drawComplicatedShape), there is a large reduction in readability when utility functions such as these come first.

The temptation would be to expose these on the object even though they are not used outside the object just to better organize the file. This prevents things like Google compiler from optimizing them like it would if they were locally scoped.

It would be nice at least, even if you disagree with the practice, the message be correct and not say it is a global, but give a warning and let that warning be able to be switched off.

using node:true continues not accepting __dirname

Using node: true continues not accepting __dirname while Disallow dangling _ in identifiers is checked

/*jslint devel: true, node: true, nomen: true, maxerr: 50, indent: 4 */

console.log(__dirname);

Error:
Problem at line 1 character 13: Unexpected dangling '_' in '__dirname'.
console.log(__dirname);

source: jslint.com live editor

Tri-state checkboxes with the indeterminate attribute instead of tables, spans, and styles?

I love the idea of using a tri-state checkbox for developing the options string, but the new UI for JSLint doesn't look very good, especially from an accessibility standpoint.
Perhaps using the indeterminate attribute for the input checkbox element would result in a better program design.
Using the indeterminate attribute would make the site look significantly cleaner in HTML and JS code instead of using tables and spans and setting styles.

README - Add example how to run program locally

The READMe mentions:

"JSLint can be run anywhere that JavaScript (or Java) can run. See for example
http://tech.groups.yahoo.com/group/jslint_com/database?method=reportRows&amp;tbl=1"

However, the URL can't be followed because some weid Yahoo login screen appears to ask to join the mailing list (web group?) before the message can be viewed. I certainly am not interested in joining anything I just want to view.

Please consider addign the relevant information to README how to run JsLint from stanalone -- command line.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.