jslint The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype

jslint The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype. This jslint warning message will show up when you looping through the keys using the for in loop without check if the key is object’s own property. For example, jslint will give you this warning in this this code snippet

/*global console*/
/*jslint node: true*/
"use strict";

Object.prototype.someStr = 'some String';

var book = {
        name: "bible",
        page: 999
    };

var key;
for (key in book) {
    console.log(key);
}
//the for in loop prints
//name
//page
//someStr

You can see that without check if the key belongs to the object itself, the for in loop will get the key someStr that is inherited from the Object.prototype. Thus, jslint will giving your warning “The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.”

To get rid of the warning is just adding a if check in the body of the for in loop.

/*global console*/
/*jslint node: true*/
"use strict";

Object.prototype.someStr = 'some String';

var book = {
        name: "bible",
        page: 999
    };

var key;

for (key in book) {
    if(book.hasOwnProperty(key)) {
        console.log(key);
    }
}

//the for in loop prints
//name
//page

Search within Codexpedia

Custom Search

Search the entire web

Custom Search