Explain Codes LogoExplain Codes Logo

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

javascript
for-in-loops
javascript-best-practices
prototype-inheritance
Anton ShumikhinbyAnton Shumikhin·Mar 10, 2025
TLDR

The JSLint error "body of a for in should be wrapped in an if statement" appears when you use a for...in loop without a corresponding hasOwnProperty check. Here's how to avoid it:

for (var key in obj) { if (obj.hasOwnProperty(key)) { // Safe to proceed, cap'n! } }

In a nutshell, the hasOwnProperty function includes only the object's own properties, excluding inherited ones.

Going beyond surface: for...in loops

JavaScript's for...in loop traverses over an object's properties. It, however, includes inherited properties due to JavaScript's prototype-based inheritance, a phenomenon that can lead to some spooky, unexpected results. 👻

Array vs Objects: Choose your weapon

for...in might be tempted to iterate over an array, but resist. Arrays and traditional for loops are a perfect duo. For key-value structures, for...in with a hasOwnProperty filter is your go-to choice:

for (var key in myObject) { if (myObject.hasOwnProperty(key)) { // Go wild here, but don't wake up regretting anything! 😜 } }

Defensive programming: Play it safe, kid

Your best defense against potential horror movie material includes:

  • Prototype Invasion: Safety first! Keep an eye out for unexpected properties sneaking in while using libraries or frameworks that extend prototypes.
  • Inheritance Inspections: Engage hasOwnProperty to sift out inherited properties, keeping focus on the object's personal belongings.
  • Strict Comparison: JavaScript is a loose cannon. Ensure to use === to avoid type coercion blindsides.

jQuery for the save

If jQuery is a part of your toolkit, enjoy a clean ride with $.each():

$.each(myObject, function(key, value) { // Enjoy the smooth ride, BUT keep your seatbelts fastened ✌️ });

However, JavaScript isn't the wild west anymore. Stannis-approved official functions like Object.keys, Object.entries, and array iteration functions offer safer alternatives.

ES6: Future is here

With ES6, the Object.keys() and Object.entries() methods allow safe traversal over an object's properties, almost rendering for...in loops obsolete.

Object.keys(myObject).forEach((key) => { // Get in! We're going iterating. });

For a solid, Crockford-approved set of practices, check out Douglas Crockford's video series. Also, the Airbnb JS Style Guide has some pretty nifty tips for typists of all kinds.