Create empty object or object with null values for already known keys

Problem

I am playing around with JavaScript and AngularJS since a few days and I am not sure about the following:

I am working on a sample project in which a user is able to create a new car with just a few properties stored in an JS object like this:

var car = {
    color: 'black',
    seating: 'leather',
    fuelconsumption: 'moderate'
}

The user can create a new car by clicking on an add-button. Angular then creates a new instance of a car and the user can specify the wishes for new car.

However, should I create an empty object like

var car = {}

and add the needed keys using the bound text inputs or should I do something different?

Since the properties of a new car are known a-priori I could also create an object with the needed keys and null as their values like this:

var car = {
    color: null,
    seating: null,
    fuelconsumption: null
}

Which way would be more preferable due to e.g. best-practise?

Problem courtesy of: albert

Solution

In Javascript, there is often not a need to initialize a property to null. This is because referencing a property that has not been initialized just harmlessly returns undefined which can work just as well as null. This is obviously different than some other languages (Java, C++) where properties of an object must be declared before you can reference them in any way.

What I would think might make sense in your case is to create a constructor function for creating a car object because you will presumably be creating more than one car and all possible car objects won't be known at the time you write the code. So, you create a constructor function like this:

function Car(color, seating, fuel) {
    this.color = color;
    this.seating = seating;
    this.fuelConsumption = fuel;
}

Then, you can create a new Car object like this:

var c = new Car('black', 'leather', 'moderate');
console.log(c.color);   // 'black'
Solution courtesy of: jfriend00

Discussion

You can do it both ways. I prefer creating the empty object using {} and then adding the needed props but you can make it by defining the props with the initialization of the value:

 var car = {};

or

var car = { 
    color: null,
    seating: null,
    fuelconsumption: null
};

Just like you did. I dont think there is a best practise for doing this. But maybe the values shoud point the needed type of the data saved this property.

Example:

var car = { 
    color:"",
    seating: "",
    fuelconsumption: ""
};

In you case "" is fine.

If using number NaN, undefined.

If using strings "".

If using objects or arrays {} [].

If using some kind of boolen values true/false

Discussion courtesy of: Iliyan Yotov

This recipe can be found in it's original form on Stack Over Flow.