twodox
twodox

Reputation: 153

Clarify my understanding of a bit of JavaScript

I am working through a book that is all about functional javascript. In that book, there is the following bit of code:

const forEachObj = (obj,fn) =>{
    for(let prop in obj){
        if(obj.hasOwnProperty(prop)){
            fn(prop,obj[prop]);
        }
    }
};

I understand this as going through each property of an object then asking IF that object has that property then running a provided function.

What I don't understand is how the if does anything. Won't it always be true? Isn't it just asking if the prop it got from obj is a property of the obj?

Upvotes: 6

Views: 88

Answers (4)

jo_va
jo_va

Reputation: 13964

To complement the answers already posted, getting all the propeties of an object and then filtering using hasOwnProperty() is equivalent to using Object.entries() to get a list of all the enumerable own properties of an object. All properties which are not inherited from its ancestors.

You can also do the same using Object.keys().

const forEachObj1 = (obj, fn) => {
    for (let prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            fn(prop, obj[prop]);
        }
    }
};

const forEachObj2 = (obj, fn) => Object.entries(obj).forEach(([key, val]) => fn(key, val));
const forEachObj3 = (obj, fn) => Object.keys(obj).forEach(key => fn(key, obj[key]));

const obj = { a: 1, b: 2 };
const func = (key, val) => console.log(key, val);

forEachObj1(obj, func);
forEachObj2(obj, func);
forEachObj3(obj, func);

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

The for...in operator operates over all the properties in an object's prototype chain - hasOwnProperty() checks if that object itself has the property, and it's not inherited. From MDN:

unlike the in operator, this method does not check for a property in the object's prototype chain.

Upvotes: 0

jakemingolla
jakemingolla

Reputation: 1639

From the MDN

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

Lots of properties (toString, for example) are inherited but likely not something you would want to iterate over when checking keys defined on an object.

Upvotes: 5

Ele
Ele

Reputation: 33726

This obj.hasOwnProperty(prop) is asking if prop belongs to the Object itself and is not an inherited property.

Upvotes: 0

Related Questions