Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lambo823's avatar

How did this get log before I defined it?

Hello everyone,

Let's say I have this object (I mean, constructor function with which I create a new object)

const Person = function (firstName, birthYear) { this.firstName = firstName; this.birthYear = birthYear; }; Now, I accidentally realized that if I for example want to add a method on Person I can console.log it before it was defined, so, how is that possible? So, what I mean is: https://routerlogin.uno/

console.log(Person.prototype); //it shows that Person already contains calcAge function before it was defined

Person.prototype.calcAge = function () { console.log(2037 - this.birthYear); }; I expected some error because of that, but for some reason everything worked fine.

0 likes
2 replies
tisuchi's avatar

@lambo823

When you do:

console.log(Person.prototype);

It doesn't show any calcAge method because at this point in the code, you haven't added it yet. JavaScript does not hoist the assignment of properties/methods on objects.

Afterwards, when you do:

Person.prototype.calcAge = function () {
  console.log(2037 - this.birthYear);
};

You're adding the method calcAge to the Person.prototype object. This assignment doesn't need to be hoisted because it's not a declaration - it's just an assignment of a property to an object.

Please or to participate in this conversation.