0

Why does javascript return this type error:

TypeError: Cannot use 'in' operator to search for 'active' in undefined

when I do something like this

foo = [ 
          {link:"http1", active:"true"}, 
          {link:"http2", active:"true"}, 
          {link:"http3"}  
      ]

    var checker = function(){

        for(i=0; i<= foo.length; i++){ 
            if('active' in foo[i]){
                checked = true
            }
        }
    }

but when I do this in the console with the same foo object

'active' in foo[0]

it returns true?

2
  • JavaScript best practice: don't use in. JavaScript has supported what you're trying to do since forever as simply if (foo[i].active) { ... }, or if the property is in a named variable, let's pretend we have one call "propname", if (foo[i][propname]) { ... }. And for sanity, you do if (foo[i] && foo[i].active) { ... } Sep 6, 2014 at 1:23
  • Thank you. Coming from python it seems normal to do 'in' but I see what you're saying
    – Garuuk
    Sep 6, 2014 at 2:41

1 Answer 1

2

The error says the expression foo[i] is undefined - because, the expression does evaluate to undefined. (Hint: i = 4).

Trivially the issue is reproducible with 'active' in undefined, no loop required.

The cause in this case is an incorrect condition for the loop: it should be i < foo.length, so i goes 0..3 and not 0..4.

The code should likely also use a local i (thanks RobG!), a break (when checked is set), return a value from the function (instead of using a presumed global), and/or be replaced with Array.some.

Now also closing as "a typographical error"..

2
  • Ahhh dang didn't catch that. Yup makes sense, I should have checked to make sure the checked value was true first.
    – Garuuk
    Sep 6, 2014 at 0:00
  • 2
    Consider keeping variables local, especially counters: for (var i=0, iLen=foo.length, checked=false; i<iLen && !checked; i++) {checked = !!foo[i] && 'active' in foo[i]} or something like that.
    – RobG
    Sep 6, 2014 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.