Different Ways To Create Object In Javascript

Mohan pd.
Written by Mohan pd. on
Different Ways To Create Object In Javascript

Here are the different ways to create Javascript object.

Using object constructor.

By letting values/keys get decided later in the code

var data = {};
data.first_name = 'John';
data.last_name = 'doe';
data.email = '[email protected]';

Using object literals.

By setting up values/keys up front while declaring the object

var data = {
  data.first_name = 'John',
  data.last_name = 'doe',
  data.email = '[email protected]'
  };

Note: we may extend that for a more OO way so that we could template objects.
In example, by using data as a function and calling new on it for every object.

function datum(first_name, last_name, email) 
{
  this.first_name = first_name,
  this.last_name = last_name,
  this.email = email
}
data =new datum(first_name, last_name, email);

Third Way:

This way is similar to the first one, but a bit more dynamic

var data = {};
data['first_name'] = 'John';
data['last_name'] = 'doe';
data['email'] = '[email protected]';

In example: if we have dynamic property name we may do

function datum(first_property, second_property, third_property, val1, val2, val3)
{
  var data = {};
  data[first_property] = val1;
  data[second_property] = val2;
  data[third_property] = val3;
  return data;
};
data = datum(first_name, last_name, email, 'John', 'doe', '[email protected]');
Mohan pd.

Mohan pd.

Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Comments

comments powered by Disqus