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

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(){


Third way — JavaScript objects using array syntax:
var NewObject = {};

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


Solution 1:

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

  • Use way 1 if you want to create several similar objects. In your example, Person (you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.
  • Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
  • Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.

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:

Related:  Forcing windows resize to fire

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;

Solution 2:

There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-

  1. Object Constructor
  2. Literal constructor
  3. Function Based
  4. Protoype Based
  5. Function and Prototype Based
  6. Singleton Based


  1. Object constructor
var person = new Object();

person.name = "Anand",
person.getName = function(){
  return this.name ; 
  1. Literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name
  1. function Constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  1. Prototype
function Person(){};

Person.prototype.name = "Anand";
  1. Function/Prototype combination
function Person(name){
  this.name = name;
Person.prototype.getName = function(){
  return this.name
  1. Singleton
var person = new function(){
  this.name = "Anand"

You can try it on console, if you have any confusion.

Solution 3:

There is no “best way” to create an object. Each way has benefits depending on your use case.

The constructor pattern (a function paired with the new operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don’t. So if you want prototypal inheritance, then a constructor function is a fine way to go.

However, if you want prototypal inheritance, you may as well use Object.create, which makes the inheritance more obvious.

Creating an object literal (ex: var obj = {foo: "bar"};) works great if you happen to have all the properties you wish to set on hand at creation time.

For setting properties later, the NewObject.property1 syntax is generally preferable to NewObject['property1'] if you know the property name. But the latter is useful when you don’t actually have the property’s name ahead of time (ex: NewObject[someStringVar]).

Related:  Remove an attribute from a Backbone.js model

Hope this helps!

Solution 4:

I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you’re planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.


function Circle(radius) {
    this.radius = radius;
Circle.prototype.getCircumference = function() {
    return Math.PI * 2 * this.radius;
Circle.prototype.getArea = function() {
    return Math.PI * this.radius * this.radius;

I am not a big fan of the third method, but it’s really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];.

Solution 5:

There are a many ways to create your objects in JavaScript.
Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.

Constructer functions

There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:

function Box (Width, Height, fill) {  
  this.width = Width;  // The width of the box 
  this.height = Height;  // The height of the box 
  this.fill = true;  // Is it filled or not?

and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:

var newBox = new Box(8, 12, true);  

Object literals

Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:

var person = { 
    name: "Alireza",
    surname: "Dezfoolian"
    nose: 1,  
    feet: 2,  
    hands: 2,
    cash: null


Related:  How do I upload a file with the JS fetch API?

After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:

Box.prototype.colour = 'red';

Solution 6:

Of course there is a best way.Objects in javascript have enumerable and nonenumerable properties.

var empty = {};
// . function toString(){...}
// . [object Object]

In the example above you can see that an empty object actually has properties.

Ok first let’s see which is the best way:

var new_object = Object.create(null)

new_object.name = 'Roland'
new_object.last_name = 'Doda'

console.log("toString" in new_object) //=> false

In the example above the log will output false.

Now let’s see why the other object creation ways are incorrect.

//Object constructor
var object = new Object();

console.log("toString" in object); //=> true

//Literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name

console.log("toString" in person); //=> true

//function Constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name

var person = new Person ('landi')

console.log("toString" in person); //=> true

function Person(){};

Person.prototype.name = "Anand";

console.log("toString" in person); //=> true

//Function/Prototype combination
function Person2(name){
  this.name = name;

Person2.prototype.getName = function(){
  return this.name

var person2 = new Person2('Roland')

console.log("toString" in person2) //=> true

As you can see above,all examples log true.Which means if you have a case that you have a for in loop to see if the object has a property will lead you to wrong results probably.

Note that the best way it is not easy.You have to define all properties of object line by line.The other ways are more easier and will have less code to create an object but you have to be aware in some cases.
I always use the “other ways” by the way and one solution to above warning if you don’t use the best way is:

 for (var property in new_object) {
  if (new_object.hasOwnProperty(property)) {
    // ... this is an own property