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'
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'
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
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.
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.