Skip to main content
InterviewHubPRO
Section Overview
Q223

Question 223 of 536

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

42%
JavaScript & V8 Internals (536 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

What is the difference between get and defineProperty

junior LevelMost AskedCode ExampleEvent LoopPrototypes

Both have similar results unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.

Practical Code Example

javascript
// 1. Using getter in object literal syntax:
const user = {
  first: 'John',
  last: 'Doe',
  get fullName() { return `${this.first} ${this.last}`; }
};
console.log(user.fullName); // 'John Doe'

// 2. Using Object.defineProperty (allows setting enumerable, configurable):
Object.defineProperty(user, 'greeting', {
  get() { return `Hello, ${this.fullName}`; },
  enumerable: false
});
console.log(user.greeting); // 'Hello, John Doe'