Due to object in javascript is associative map (HashMap in other programming languages) does next code
for (var prop in object) {
if (prop === someConc
This can be tested empirically:
<script language="javascript">
alert("Initialising test object...");
var obj = new Object();
for (var i=0; i<1000000; i++) obj["prop"+i] = i;
alert("Initialised. Doing Test.");
var d1 = (new Date()).getTime();
needle = obj["prop"+(i-1)]; // last object
for (var prop in obj) {
if (obj === needle) {
// some decision
break;
}
}
var ms1 = ((new Date()).getTime()) - d1;
alert("Method 1 took "+ms1+"ms.")
var d2 = (new Date()).getTime();
if (typeof obj["prop"+(i-1)] != 'undefined') {
// some decision
}
var ms2 = (new Date()).getTime() - d2;
alert("Method 2 took "+ms2+"ms.")
</script>
Method 1 takes MUCH longer than Method 2. This is hardly surprising since all of the computing necessary to execute Method 2 is included in Method 1 plus MUCH more.
The answer to this question becomes obvious when you understand how property lookup works in JavaScript. In the worst case, properties in JavaScript Objects are implemented as elements in a hash table.
Property lookup is, in this case, performed in constant time on average. It's good to note, though, that in very rare worst-case scenarios, hash table search time can be linear.
If you loop through a list of properties, you reduce the performance to linear time, roughly proportional to the number of properties in the object.
So, yes method 1 is always faster, and much much faster if the object has lots of properties.
Just as a side note: many modern JavaScript engines (i.e. Google's V8) may optimize your code for you to provide better performance. In fact, I believe Objects in V8 are implemented as real classes. In this case memory lookup is guaranteed to be constant time, unlike traditional hash table lookup.
I guess for the first one you meant:
if ('prop' in obj) {
// ...
}
Then you can talk about speed differences and different behavior.
Homework:
var obj = { prop: undefined }; // a bit philosophical...