javascriptstringnull

Why does JavaScript sometimes convert null to empty string and sometimes to "null" string?


I'm studying JavaScript and I'm confused about the following:

document.getElementById("demo").innerHTML = typeof (document.getElementById("demo").innerHTML);

It assigns "string" to an HTML element. OK. So then I suppose when I will try to assign some value of different type (not string) it will be converted to string first:

document.getElementById("demo").innerHTML = null; //null will be converted to string first

like this:

document.getElementById("demo").innerHTML = String(null);

HTML element gets en empty value in the first example. But the second example returns "string". Why? This tutorial http://www.w3schools.com/js/js_type_conversion.asp says that String(null) returns "null", but not empty string. As I see it's true only for the second example.

How to understand this confusing conversion behavior of JavaScript? Why doesn't the first example return "string"?

Edited:

Now partially I understood it. JS uses toString() but not String(). And toString() returns empty string for null. So now my question is: Why toString() and String() produce different values?

Edited 2:

Examples:

document.getElementById("demo").innerHTML = String(null); //returns an empty string 
document.getElementById("demo").innerHTML = null.toString(); //returns "null" string

Solution

  • I don't think there's a real convention here; Element.innerHTML is a property that tests the given value to determine what to do. In Safari it behaves like this:

    if (value === null || value === '') {
        // remove all contents
    } else {
        // parse string representation of value into the elements contents
    }
    

    So both "" (empty string) and null are considered the same and the assignment will just remove all contents; I couldn't find conclusive evidence that would suggest other browsers work this way, but it seems very likely that it should be considered an implementation detail that you shouldn't rely upon (see update).

    That said, the documented way of clearing an element is by assigning the empty string to this property.

    Update

    I've found this (inconclusive) email thread about the subject, highlighting that this behaviour is not standardised:

    For .innerHTML = null Opera and Internet Explorer act as if the literal string "null" was used. Firefox acts as if "" was used.