4. Adding properties


#1

var friends = {

var bill = new Object ();
    bill.firstName = "Bill";
    bill.lastName = "Gates";
    bill.number = "343";

var steve = new Object ();
    steve.firstName = "Bill";
    steve.lastName = "Gates";
    steve.number = "323";

};

Error is : SyntaxError: Unexpected identifier

Thank you for your help!


#2

You need to define the array first then create the objects:

var friends = {};

var bill = new Object();
// Blah blah, stuff about Bill
var steve = new Object();
// Blah blah, stuff about Steve

#3

Cheers, found what the problem was.
Tried a different approach and it worked.
Thanks again!


#4

The code inside the friends object is not the expected literal syntax. You could leave it as is, just close the friends block.

var friends = {};

// bill and steve code

friends.bill = bill;
friends.steve = steve;


#5

Thank you!
did it so:

var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555"
},

steve: {
    firstName: "Steve",
    lastName: "Jobs",
    number: "(206) 666-5555"
}

};


#6

Much simpler way, isn't it?


#7

Indeed. I've tried that first, but forgot the commas after the { so Iv'e changed the strategy.


#8

I've been trying to use new Object(); as such:

var friends = new Object();
    friends.bill = new Object();
    friends.steve = new Object();

this passes 3. Adding your friends but this way doesn't seem to allow me to add the properties. I've tried multiple ways so I do not know if this isn't an acceptable way or my syntax is wrong or something else. Has anyone else tried this way?


#9

@osiris technically you would do it this way:

var friends = new Object();
friends.nick = new Object();
friends.nick.superPower = "Devilishly Handsome Looks";

console.log(friends.nick.superPower);

But, as objects in Javascript are mutable, you can then create references to objects. For example, var x = y means that x is a reference to y, rather than a copy.

So with the addition of the example above:

var myFriend = friends.nick;
myFriend.reasonHeIsGreat = "Everything";
console.log(myFriend.reasonHeIsGreat);

Nonetheless, using the object literal notation {} is always advised when creating objects in Javascript.