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

Different Ways To Create Object In Javascript

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

1
2
3
4
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

1
2
3
4
5
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.

1
2
3
4
5
6
7
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

1
2
3
4
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

1
2
3
4
5
6
7
8
9
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]');

comments powered by Disqus