Search code examples
javascriptnullprototype

Is it possible to add a method to the prototype of the null value?


I think I know the answer to this question already, but I'm looking for confirmation.

What I would like to do is call toString() on a variable and if null return an empty string. I know I can convert null to "null" with String(null), but that seems so ugly if I want to do something like this:

var amount = myPossiblyNullVar.toString().toFloat();

or even more simply

var amount = myPossiblyNullVar.toFloat();

Where I have defined toFloat() as

String.prototype.toFloat = function() {
  var float;
  float = parseFloat(this.cleanNum());
  if (isNaN(float)) {
    return null;
  } else {
    return float;
  }
};

Based on what I have read, it seems that extending NULL in JavaScript is not possible. Can anyone confirm this or provide an alternative that I haven't thought of?


Solution

  • You do not want to modify the JavaScript null prototype.

    var amount = maybeNull ? maybeNull.toFloat() : null;
    

    If you have null propagation support (ES7)

     var amount = maybeNull?.toFloat();
    

    If maybeNull is null, ?. will return null instead of trying to call toFloat().