Code accepted but I want to understand why


The most recent version of my code that was accepted is below. Is it correct / best practice to declare the object as a variable first, and then create the array – like I did here – or is there a more common way?

var myObject = {
    firstName: "Well",
    lastName: "Quellquell",
    age: 43

var myArray = [


Arrays and objects are reference objects that exist in only one place. Above, myObject is not actually in the array, it is only referred from an element in the array. This is dangerous because the integrity of the array is not guaranteed.

 > myObject.age = 25
=> 25
 > myArray[3]
=> { firstName: "Well", lastName: "Quellquell", age: 25 }

Or worse, myObject gets overwritten with a value or another object that does not have the same attributes. We could break our program. Better that the object be written directly to the array.

myArray.push({ firstName: "Well", lastName: "Quellquell", age: 43 })

This will install the object in the array, safe from outside effects.


Ooh, I see. I retract my statement :sweat_smile:.


No need to. You raise a valid point, that of creating the object before including a reference in the array. If the object does not exist when the array is defined, it will raise an exception. My comment goes over and above the scope of the lesson and speaks to protecting our data structures. In a more advanced environment, such as a closure, our data objects would be protected from the outside, and the global object would be protected from our program. But that is a topic for way down the road.


Thanks for your careful explanation, mtf – that does sound like an important distinction!

I notice that you use ".push" in your suggested answer – I'm familiar with this method from other projects outside of Codecademy, but as far as I can tell, it's not how this lesson is expecting us to solve the task.

Do you think it would also work if I wrote:

var myArray = [
    myObject = {firstName: "Well", lastName: "Quellquell", age: 43}

...? I guess I'm wondering how the most standard code for including an object in an array looks, exactly – especially at this point in the progression of the course.


This should raise an error. I agree, the lesson does not expect array.push(). Simply write the object without a variable assignment.

var myArray = [
    {firstName: "Well", lastName: "Quellquell", age: 43}


Ah, okay! So it looks like the rule here is: if you put something in curly brackets within an array, it will automatically be interpreted as an object?


That's correct. Even if it is left empty. {} is still an object.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.