Search code examples
javascriptnullliteralsobject-literalmember-initialization

Is using null to declare literal members for later initialization a viable praxis in JS?


I'm going to declare a literal as follows:

var obj = {
    x: null,
    init: function (pX) {
        this.x = pX;
    }
};

Objections?

I'd like to do that because x: undefined would be the same as not declaring x at all. Whats a good practice when declaring literal members for later initialization?


Solution

  • If you need the property to exist as a placeholder for some reason, null is as good a value as any. You can use any value that is different enough from what it's going to contain when initialised, and that is comparable.

    Example:

    var obj = {
      x: null,
      init: function (pX) {
        if (this.x == null) {
          this.x = pX;
        }
      }
    }
    

    If you don't need to check the value of the placeholder (or for some other odd reason), then you don't need the placeholder either. It's perfectly valid to create the property by assigning a value to it:

    var obj = {
      init: function (pX) {
        this.x = pX;
      }
    }