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?

3
  • age is not a variable, it's a property. Commented Sep 11, 2017 at 10:50
  • Btw, we have 2017 :-) Commented Sep 11, 2017 at 10:50
  • I know, the course was released in 2016 and I'm following along to make sure I understand the principle first. :-) Commented Sep 11, 2017 at 10:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

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?
in the #1 output it is not logged, after adding it to this it would be logged every time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.