All sample questions / JavaScript
What does console.log(obj.hasOwnProperty('a'), obj.hasOwnProperty('toString')) print? JavaScript this, Prototypes and Classes
Block 3, this, Prototypes and Classes, question 8 of the JavaScript sample
const obj = { a: 1 };
console.log(obj.hasOwnProperty('a'), obj.hasOwnProperty('toString'));
What does this print?
Show the answer and why each option is right or wrong
Answer, A. true false
- A. true false
- Correct. a is an own property of obj, while toString is only reachable through the inherited Object.prototype, so hasOwnProperty reports it as false.
- B. true true
- Assumes hasOwnProperty reports true for anything reachable on the object, whether it lives directly on the object or somewhere up its prototype chain. hasOwnProperty deliberately ignores inherited properties, it only checks the object itself.
- C. false false
- Assumes toString somehow fails to exist on obj at all, when it is reachable through Object.prototype and calling obj.toString() would work fine. hasOwnProperty is about where a property lives, not about whether it can be accessed.
- D. false true
- Assumes the order is reversed, that the built in toString counts as owned while the literal property a does not. a was written directly into the object literal, making it the clearly own property, while toString only comes from the shared prototype.
hasOwnProperty checks only the properties that live directly on the object it is called on, completely ignoring the prototype chain. a was set in the object literal, so it counts as own. toString is never defined on obj itself, it is inherited from Object.prototype, so hasOwnProperty correctly reports false even though obj.toString() would still work through inheritance.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.