javascriptobject

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?


So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?

I also saw that in all of these examples the keyword var is not used before a property — why? Is it not necessary to declare var before the name of a property as it mentioned that properties are variables?

In the second and third way, the name of the object is in upper-case whereas in the first way the name of the object is in lower-case. What case should we use for an object name?

First way:

function person(fname, lname, age, eyecolor){
  this.firstname = fname;
  this.lastname = lname;
  this.age = age;
  this.eyecolor = eyecolor;
}

myFather = new person("John", "Doe", 50, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");

Second way:

var Robot = {
  metal: "Titanium",
  killAllHumans: function(){
    alert("Exterminate!");
  }
};

Robot.killAllHumans();

Third way — JavaScript objects using array syntax:

var NewObject = {};

NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ }

Solution

  • There is no best way, it depends on your use case.

    Update: As requested examples for the third way.

    Dependent properties:

    The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:

    var book = {
        price: somePrice * discount,
        pages: 500,
        pricePerPage: this.price / this.pages
    };
    

    instead, you could do:

    var book = {
        price: somePrice * discount,
        pages: 500
    };
    book.pricePerPage = book.price / book.pages;
    // or book['pricePerPage'] = book.price / book.pages;
    

    Dynamic property names:

    If the property name is stored in some variable or created through some expression, then you have to use bracket notation:

    var name = 'propertyName';
    
    // the property will be `name`, not `propertyName`
    var obj = {
        name: 42
    }; 
    
    // same here
    obj.name = 42;
    
    // this works, it will set `propertyName`
    obj[name] = 42;