For / in bug

2008-01-10
2013-05-28
  • Robert Burke
    Robert Burke
    2008-01-10

    Let me start by saying thank you for creating JavaScript Lint.  We have integrated it into our build system and use it all the time.

    I found a bug that is not being caught by JavaScript Lint but IS being caught by Crockford's jslint (www.jslint.com).

    This code:

    var getMapKeys = function (map) {
        var names = [];
        var name = "";
        for (name in map) {
            names.push(name);
        }
        return names.sort();
    };

    Gets flagged with this error:

    Error:
    Problem at line 4 character 5: The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.

    for (name in this._map) {

    This is a very good error, since our JavaScript code is sometimes used in conjunction with other code, and that other code modifies the prototype of Object.  This causes the names of the methods added to the prototype to be returned by getMapKeys, which is almost certainly not what was intended.

    Crockford has an article on this: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    Anyhow, it would be nice if JavaScript Lint could also pick up on this error.