-2

I'm getting this exception in the following code: TypeError: Cannot read property 'toString' of undefined

for (var key in obj) {
  var val = obj[key];
  var s = val.toString();
}

How is it possible for val to be undefined in this code?

I don't have a log of the actual data, so I'm not sure what was in obj, but it was constructed from JSON and I don't have the JSON input.

This is the actual full code:

function deepMatchKeyword(obj, keyword) {
    for (var key in obj) {
        var val = obj[key];
        if (typeof val == 'object' && !(val instanceof Array)) {
            if (deepMatchKeyword(val, keyword))
                return true;
        } else {
            var s = val.toString();
            if (s.toLowerCase().includes(keyword))
                return true;
       }
    }
    return false;
}
Scott Thibault
  • 329
  • 2
  • 4
  • 12

2 Answers2

2

How is it possible for val to be undefined in this code?

Very easily. undefined is a value like any other and can be assigned to a property.

for ... in deals with enumerable properties, not just ones with defined values.

var obj = {
  someProperty: undefined
};


for (var key in obj) {
  var val = obj[key];
  var s = val.toString();
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Oh right, that makes sense. I don't think JSON.parse would return anything like that but I do have some post-processing stuff that is maybe causing that. – Scott Thibault Feb 14 '17 at 12:12
0

It's very common to include the hasOwnProperty check in loops over properties, in order to avoid enumerable properties inherited from the object's prototype chain.

// obj is defined earlier

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        var val = obj[key];
        var s = val.toString();
    }
}

See e.g. for..in and hasOwnProperty.

Community
  • 1
  • 1
hellmelt
  • 219
  • 3
  • 6