Katia Abela
Katia Abela

Reputation: 269

Javascript clarification

Starting Javascript for the first time. Looking through some notes I found the following code on creating objects.

var foo = {};
var bar = new Object();

Then:

var foo = {
   bar:2
}

Could anyone let me know the significance of the :2 after bar? What is it referring to?

PS. Have not tried Javascript before so any help would be appreciated

Upvotes: -1

Views: 61

Answers (3)

user2672373
user2672373

Reputation:

The code snippet you mentioned in the question is intended to demonstrate different methods of creating an object.

The first method var foo = {} uses the object notation {} the second method var bar = new Object() uses the Object constructor.

Going deeper, the object foo is given an attribute bar with value 2. The contents of an object is often specified as key-value pairs.

Upvotes: 0

CharlyDelta
CharlyDelta

Reputation: 938

It just initializes a object foo with the attribute bar with the (default) value 2. It can be accessed with foo.bar and of course set with (for example) foo.bar = 3

You can initialize any kind of object with this. For example a car object which saves the amount of tires, doors, and the color:

var car = {
    amountTires: 4,
    amountDoors: 3,
    color: "red"
}

Upvotes: 1

Axel Prieto
Axel Prieto

Reputation: 595

In that context, bar would be the object's property, and '2' would be it's value.

Upvotes: 0

Related Questions