Mozilla's website clearly describes hasOwnProperty()
and the in
operator.
However, it does not give any implementation details in regards to their efficiencies.
I would suspect they'd be O(1)
(constant time) but would love to see any references or tests that might exist.
The last built-in method we will discuss for objects is hasOwnProperty. This method has an O(1) or constant time and works by returning true or false depending on if the key is present in the object.
Both also support ES6 symbols. So what's the difference between the two? The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.
The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.
The answer is O(1) if you use the formula for summation directly. Save this answer. Show activity on this post. the addition is called n times, so the whole code has a time complexity of O(1) * n = O(n).
To turn my comments into an answer.
hasOwnProperty()
should be O(1)
, as it is a key lookup, but it will be implementation specific.
in
will most certainly be more complicated (though should be the same as hasOwnProperty()
if the property exists on that object), as it goes up the prototype chain, looking for that property. That is why it is often recommended to use hasOwnProperty()
when iterating over object properties with for ( in )
.
To find out, inspect the source code of these functions. Use the source, Luke :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With