Loading ...
Sorry, an error occurred while loading the content.

1545Re: IF statement wrapper in FOR IN loops

Expand Messages
  • pauanyu
    Oct 15, 2010
    • 0 Attachment
      Note: if this is implemented, make sure it also supports this construct:

      for (var key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
      // do something...
      }
      }

      --- In jslint_com@yahoogroups.com, "Marcel Duran" <contact@...> wrote:
      >
      > Hello JSLinters,
      >
      > JSLint complains when a FOR IN loop has no IF statement wrapping its body to filter unwanted properties from prototype:
      >
      > var i, obj = {a: 1, b: 2};
      > for (i in obj) {
      > console.log(i + ': ' + obj[i]);
      > }
      >
      > Error: Problem at line 2 character 1: The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.
      >
      > In order to fix that, the most common filter is an IF statement checking the "own property" of obj:
      >
      > var i, obj = {a: 1, b: 2};
      > for (i in obj) {
      > if (obj.hasOwnProperty(i)) {
      > console.log(i + ': ' + obj[i]);
      > }
      > }
      >
      > However any IF statement passes JSLint criteria:
      >
      > var i, obj = {a: 1, b: 2};
      > for (i in obj) {
      > if (true) {
      > console.log(i + ': ' + obj[i]);
      > }
      > }
      >
      > I've recently passed a bunch of legacy code in JSLint and noticed it wasn't complaining when FOR IN loops like the following were found:
      >
      > for (i in obj) {
      > if (obj[i] > 1)
      > ...
      >
      > I know The Good Parts warns that hasOwnProperty is a method and can be replaced with a different value, this is all about "bad parts" but still, shouldn't JSLint check for obj.hasOwnProperty in the IF statement wrapping FOR IN loops?
      >
      >
      > Marcel
      >
    • Show all 2 messages in this topic