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

29,685

Solution 1

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 2

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

Share:
29,685
albert
Author by

albert

Chemical Engineer / Process Engineer - Research Assistant - Doctoral Candidate - Digital Transformation Enthusiast

Updated on November 16, 2020

Comments

  • albert
    albert over 3 years

    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?