3 ms·
> it blows up if 'age' isn't a property on one of the objects in the object No it doesn't. It will return as undefined, which evaluates to false when compared
by moron4hire 10y ago
> it blows up if 'age' isn't a property on one of the objects in the object
No it doesn't. It will return as undefined, which evaluates to false when compared to 1 using either triple- or double-equals.
And why call hasOwnProperty here? I'm pretty sure I want to know the age of any properties inherited into my object from a superclass.
At worst, I will grant you an undefined/null check:
var val = null;
for(var k in obj){
if(obj[k] && obj[k].age === 1){
val = obj[k];
break;
}
}
This works with both objects and arrays.
- jdd 10y agoI'm guessing after repeated use you'd abstract that into a function. Maybe even a collection of them.
- moron4hire 10y agoNo, why would you? It's just a loop. Not all code deduplication is a good idea.
- jdd 10y ago;)
- gnaritas 10y ago> No, why would you? Because he's a better programmer than you are, and he knows it. > It's just a loop. There are many kinds of common patterns in loops, abstracting them into resuable higher order functions, aka a collections api is rather basic functional programming; "it's just a loop" is a blub phrase of someone who doesn't see the point because they have tried it long enough to understand the value in a different paradigm.
- moron4hire 10y agoI know it's currently thought as so, but functional programming is not the be-all, end-all paradigm. If you've been around for a while, you'd have seen the ebb and flow a few times already.
- gnaritas 10y agoNo one said it was, but in this use case it's far superior to hand written loops. Virtually all modern programming languages have a functional collections API precisely because of this advantage. If you're still writing loops by hand, in nearly all cases, you're stuck in a less effective procedural programming mindset and have simply stopped updating your skills beyond the basics. If you've been around for a while, you should have already accepted the benefits of functional programming in the places it's most effective and banished low level procedural programming of loops except in cases where extreme optimization is required. There's no eb and flow here, higher order map/reduce/filter style has been the best way since the 60/70/80's when Lisp and Smalltalk were doing it.