Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object.hasOwnProperty(proName) vs lodash _.has(obj, proName) function

Tags:

I'm debating between using JavaScript Object.hasOwnProperty(propName) and lodash _.has(obj, proName) function to determine if an object has a property.

Which is more efficient for simple cases? For complex cases? For all cases?

Is there a better library that I haven't mentioned?

Thanks!

like image 732
esanz91 Avatar asked Aug 26 '15 16:08

esanz91


People also ask

What does hasOwnProperty method do?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Is Lodash an object?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise.

What is the difference between in and hasOwnProperty?

The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.

What does Lodash get do?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.


1 Answers

Well the Lodash _.has() method is just a call to Object.prototype.hasOwnProperty() after a check for a null argument. The code grabs a reference early on:

var hasOwnProperty = Object.prototype.hasOwnProperty;

and then _.has(object, prop) looks like

return object != null && hasOwnProperty.call(object, prop);
like image 163
Pointy Avatar answered Sep 22 '22 07:09

Pointy