Jim
Jim

Reputation: 53

Get the largest element at the property

I'm trying to get the largest element in the given array and the following are the requirements:

Can someone explain to me why when I put

!obj.hasOwnProperty(key)

at the end of the IF function I get the error: should return undefined if the property does not exist. But when I put it in the beginning of the IF function, it pass with no issue.

var obj = {
  key: [1, 2, 4]
};

function getLargestElementAtProperty(obj, key) {
  if (obj[key].length === 0 || !Array.isArray(obj[key]) || !obj.hasOwnProperty(key)) {
    return undefined;
  }
  var largestElement = 0;
  for (var i in obj[key]) {
    if (largestElement < obj[key][i]) {
      largestElement = obj[key][i];
    }
  }
return largestElement;
}

Upvotes: 1

Views: 50

Answers (1)

aoldershaw
aoldershaw

Reputation: 131

When !obj.hasOwnProperty(key) is put at the start of the if statement, if the object does not have the specified key (and so !obj.hasOwnProperty(key) yields true), the other checks will not be evaluated due to OR short-circuiting (briefly, if any of the conditions evaluate to true, none of the other checks are evaluated since the whole expression will always be true).

However, when placed at the end of the if-statement, obj[key].length === 0 will be evaluated first. If obj[key] === undefined, an error will occur when evaluating obj[key].length, since undefined does not have a property length. Specifically, the error is: TypeError: Cannot read property 'length' of undefined

Upvotes: 4

Related Questions