2

so, I am checking for a key in a list (hash), and I must of coded it two different ways but forget to remove a bit of it. lol. But to me, looking at it - it appears redundant. Is this the case?

 var somelist = {
      a : 'somevalue1',
      b : 'somevalue1',
      c : 'somevalue1',
      d : 'somevalue1',
      e : 'somevalue1',
      f : 'somevalue1'
 }

 for(var key in somelist ){
     if(somelist.hasOwnProperty(key)){  // <-- redundant
         // do something
     }
 }

if we are looping thru the keys - then the assumption is, it's a property of the list, yes? I want to make sure my brain isn't fried. :-)

I looked over these two posts:

for..in and hasOwnProperty

How do I check if an object has a property in JavaScript?

But my usage seems much more benign. Since I am declaring var key here, isn't it local and I don't have to worry about prototypical chain collisions?

So, it appears that in my usage - it IS redundant or not needed -- but would this be considered 'poor form'. It seems because I do not have this hash sitting in a constructor I don't have to worry about prototypical inheritance etc...

so, my two questions are:

Since I am declaring var key here, isn't it local and I don't have to worry about prototypical chain collisions?

would my usage here be considered 'poor form' even though it isn't needed? I wanted to keep with certain coding standards - but perhaps my intent is wrong here.

Community
  • 1
  • 1
james emanon
  • 11,185
  • 11
  • 56
  • 97

2 Answers2

3

It's not about the key where you have to worry. It's the object itself.

Object.prototype[1] = 1;

var somelist = {}

for (var key in somelist) {
    alert(key);
}

// '1' was alerted
Jo So
  • 25,005
  • 6
  • 42
  • 59
1

You just make your code more robust doing that check, and it is recommended as a best practice. However, to keep intendation shallow, I usually do an inverted pattern:

for( var key in obj ) {
    if( !obj.hasOwnProperty( key ) ) {
        continue;
    }

    // do something
}

Jo So pointed out a potential conflict, but also your data might just change and then your code can break. A golden rule in software development: Expect failure.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100