Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: JSLint error "The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype"

I'm using the JSLint tool to ensure my JavaScript is "strict".

I'm receiving the following error but don't understand how to fix it:

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

For the following code:

for (var i in keypairs) {     ... } 

Anyone have any ideas how to fix this to that it's JavaScript "strict" and won't be flagged by JSLint

like image 953
HeatherK Avatar asked Nov 12 '10 16:11

HeatherK


2 Answers

If keypairs is an array, then you should really iterate over the elements like:

for(var i = 0; i < keypairs.length; i++) {   ... } 

If keypairs is a hash, then JSLint is correctly recommending that you check that you are operating on the appropriate key type (i.e., confirming that the hash is the expected type)

so something like

for(var i in keypairs) {   if(keypairs.hasOwnProperty(i)) {     ...   } } 

where the if is validating whatever criteria ensures that you are not accessing a prototype function etc.

like image 157
Chris Baxter Avatar answered Sep 21 '22 15:09

Chris Baxter


It wants you to use hasOwnProperty.

for (var i in keypairs) {     if(keypairs.hasOwnProperty(i))     {         // Use i     } } 

Like much of JSLint, this is a recommendation, and its applicability depends on your situation. It is useful if there are undesired enumerable properties in the object's prototype. This might be the case if you e.g. use certain JavaScript libraries.

like image 27
Matthew Flaschen Avatar answered Sep 21 '22 15:09

Matthew Flaschen