I am creating a function that checks:
- If the array is empty, it should return undefined.
- If the property at the given key is not an array, it should return undefined.
- If there is no property at the key, it should return undefined.
So what I did is that I created an if statement using || operator to separate the cases:
function getFirstElementOfProperty(obj, key) {
if(obj.key.length === 0 || !obj.key.isArray || !obj.key.hasOwnProperty(key)){
return undefined;
}else{
return obj.key[0];
}
}
var obj = {
key: [1, 2, 4]
};
For some reason, this doesn't work. It also saying that "It Cannot read property 'length' of undefined"
.
Any idea what am I missing here?