26. Arrays of Objects (JS why printing last item?)


#1

Hi folks,

I got my code to work but I'm just wondering why in an array the last object get's printed as though there is a console.log(). Can anyone please explain?

My code:
// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}

// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
// add the last family member, "timmy", who is 6 years old
family[3] = new Person("timmy", 6);
family[3] = new Person("tommy", 3);

Thanks in advance for any feedback you can provide!

Alex


#2

The value of the last executed statement is always printed to the console. You can just ignore that.

An assignment returns the assignend value.


#3

@eveat, thanks for your reply. I guess I'm just being obsessive, but I was hoping there was a 'logical' reasoning for why the last statement is printed. Does it have to do with it's position in the code?

Is it because it is last statement in a specific type of situation? I thought typically 'return' wouldn't print and that a console.log() was typically required to print a statement to the console. 'Returning' a statement is executing it, right? But 'returning' the last statement doesn't always seem to result in printing it.

I hope I'm explaining this right. Thanks again!
Alex


#4

Yes it is always the value of the last statement that is reached.

It's similar to when a function returns something with the return keyword.

var my_variable = 10;
console.log(my_variable = 2);

The my_variable = 2 part assignes a new value to my_variable, but it also "gives back" the value of the assignment to conoloe.log(). So this program would print 2 to the console.

It would even do this without the console.log() part because of the last reached statement thing.


#5

Thanks @eveat, sounds good :slight_smile: