Why would this code not work?


#1

Hi! My name is Nelly and I am just starting to learn the basics of JavaScript! :smile:

I have attached a screenshot of a piece of code. This was not the way it was suggested by the tutorial guide but I was wondering why this alternate form would not work.

My thought process was, to create an object 'friends', and then add empty objects 'bill' and 'steve' as properties to 'friends'. Subsequently, to add the properties 'firstName', 'lastName', and 'number' to 'bill' and 'steve' objects individually.

It appeared to make sense to me, but what would be the reason it is syntactically wrong?

Thank you so much beforehand!


#2

Wow @nliupeng, as i look from my code your format and my format are completely wrong...
This is what i did:

I created a array friends with its "Friends":

var friends = {

    Bill: {

    },

    Steve: {

    }
}

Then i put the properties

var friends = {
    Bill: {
        //Now we add properties for Bill here
        firstName: "Bill", //This comma seperates the properties of friends.Bill
        lastName: "Gates",
        number: 54845645645
    }, //This comma seperates the properties of friends
    Steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: 5665464564
    }
};

Hope this helped!


#3

Thank you for your reply @amanuel2 ! In later lessons it was explained by Codecademy that properties of objects are hidden from access by external code, so in my example, to access 'bill' and 'steve' I would have to write
friends.bill.firstName = 'Bill';
friends.steve.firstName = 'Steve';

but thanks again for your reply! The way you did it seems more organized and clear! I appreciate your response!