My goal is to determine the largest element in a given array while following these requirements:
- If the array is empty, the function should return undefined.
- If the property at the specified key is not an array, it should also return undefined.
If there is no property for the key provided, the function should still return undefined.
var obj = { key: [1, 2, 4] };
I'd like some assistance understanding why when I include the code snippet:
!obj.hasOwnProperty(key)
at the end of the IF statement within the function, I encounter an error stating: "should return undefined if the property does not exist." However, when I move it to the beginning of the IF statement, the function runs without any issues.
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;
}