Transforming Null into Empty String in JavaScript

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

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.

How to convert null to empty String in Ionic React?

you can try something like this:

const data = {

phone: phone || "",

};

Javascript how to set null/undefined values in an Object to an empty string

You can use _.mapValues() to iterate the values and replace them, and _.isNil() to check if a value is null or undefined: