Why do we always need to check if an object has a key? - JS

I have the codes below.

var obj = {
  name : 'Krysten',
  age : 33,
  hasPets : false
};

function listAllValues(obj) {
  // your code here
  var array = [];
  for(var key in obj) {
    if(obj.hasOwnProperty(key)) {
        var value = obj[key];
        array.push(value);
    }
}
  console.log(array);

}

listAllValues(obj);

      

I want to focus on this code:

for(key in obj) {
    if(obj.hasOwnProperty(key)) {

    }
}

      

Why do we always need to check if obj

its own key has properties? It doesn't seem clear to me. Anyone who can explain this to me in layman terms? Sorry dummy here.

+3


source to share


2 answers


hasOwnProperty

check is property

the object itself. It can also be a property of the prototype... This way you are checking if the property belongs to the current object and not to the prototype.

Example

I have object

that has prototype

. With clean, for in

it prints all properties as well as those in prototype

(id). But with the second, it only prints those that belong to the object itself.



var parent = {
    id: 1
};

var obj = {
   name: 'Test',
   age: 18
};

Object.setPrototypeOf(obj, parent);

// All properties, also the prototype's. See the `id` property
console.log('All properties');
for(var key in obj){
    console.log(key);
}

console.log('Only it\ properties');
// All properties that belong only to object
for(var key in obj){
    if(obj.hasOwnProperty(key)) {
       console.log(key);
    }
}
      

Run codeHide result


+9


source


These are leftovers from darker times, when JS was not so smooth and its developers were more crude. When all extended basic prototypes , and we had no way to define non-enumerable properties .

So, you never knew what properties ended up on your objects due to inheritance; that when we presented this practice of checking its own property. This was also the beginning of a bad practice of distributing foreign prototypes.



But these were rougher, darker times. There are times when you need mental strength to write JS. When you needed wisdom to write a function that worked in multiple browsers, and the nerves started getting closer or even modifying some code elses never knowing what you might inflict on you. 😁

For the time being, I will immediately discard someone else's library that is so ruthless as to randomly modify basic prototypes (with very few exceptions), especially if those extensions do not enumerable:false

.

+3


source







All Articles