2

I'm working through a JavaScript course and I'm curious how the code know to include an age value above the object properties when I log it out to console? Here is the code from the lesson:

var john = {
    name: 'John',
    lastName: 'Smith',
    yearOfBirth: 1990,
    job: 'teacher',
    isMarried: false,
    family: ['Jane', 'Mark', 'Bob'],
    calculateAge: function() {
        this.age = 2016 - this.yearOfBirth;
   }
};

john.calculateAge();
console.log(john);

If I understand correctly, I create an age variable in this line:

this.age = 2016 - this.yearOfBirth;

When I look in my console, the age property and its value are stated above the object properties. What determines this presentation?

Kalamarico
  • 4,668
  • 22
  • 44
  • 67
Paul Jacobson
  • 75
  • 1
  • 9

2 Answers2

2

There is no age variable in your example. This line:

this.age = 2016 - this.yearOfBirth;

adds a property age to an object referenced by john variable.

And object properties are not ordered. It means that inside the program the age property is not above all others. It also means that you cannot be sure that when using iterative constructions like for..in the age will be at the top.

When I look in my console, the age variable and its value are stated above the object properties.

If you use console.log to show the object it uses formatting that orders keys by alphabet. Try using different name, for example, xge and you will see that it will be outputted close to the bottom.

Max Koretskyi
  • 85,840
  • 48
  • 270
  • 414
1

As you can see the below snippet you are creating the variable age and adding it as a property of this

var john = {
 name: 'John',
 lastName: 'Smith',
 yearOfBirth: 1990,
 job: 'teacher',
 isMarried: false,
 family: ['Jane', 'Mark', 'Bob'],
 calculateAge: function() {
 console.log('#1', this);
 this.age = 2016 - this.yearOfBirth;
 console.log('#2', this);
 }
};

john.calculateAge();
console.log(john);
marvel308
  • 9,593
  • 1
  • 16
  • 31
  • Thanks, I understood that. When I log this to console, it shows me the new `age` variable above the object properties. Is that just how the `age` variable is logged by default? – Paul Jacobson Sep 11 '17 at 10:49
  • in the #1 output it is not logged, after adding it to this it would be logged every time – marvel308 Sep 11 '17 at 10:50