2

When I have an array like var user = { name : 'Bob'}; what is the difference when using the following instruction?

localuser = user.name;
localuser = 'name' in user ? user.name : 'bob';
localuser = user.hasOwnProperty('name') ? user.name : 'bob'
Paul Sullivan
  • 2,865
  • 2
  • 19
  • 25
Haven
  • 7,808
  • 5
  • 25
  • 37
  • 1
    `{ name : 'Bob'}` is an object literal. *in* returns true if a property is on an object **or** its `[[Prototype]]` chain. *hasOwnProperty* returns true only if a property is on the object itself and false if it's on the `[[Prototype]]` chain or not on the object at all. – RobG Apr 28 '14 at 12:58
  • duplicate question. read this article. http://stackoverflow.com/questions/13632999/if-key-in-object-or-ifobject-hasownpropertykey – Curry Apr 28 '14 at 12:58
  • @EveryEvery yeah you are right, I see that – Haven Apr 28 '14 at 13:06

1 Answers1

6

Example:

var o = { 'foo': 'bar' };

console.log('constructor' in o); // TRUE
console.log('foo' in o); // TRUE

console.log(o.hasOwnProperty('constructor')); // FALSE
console.log(o.hasOwnProperty('foo')); // TRUE

hasOwnProperty

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

in

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

The in operator returns true if the specified property is in the specified object.

Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94