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
:
const obj = { a: '23', b: 'Red', c: null,}
const result = _.mapValues(obj, v => _.isNil(v) ? '' : v)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Related Topics
How to Remove Errors Warnings from Console
Handling Multiple Http Responses One by One in Angular 6
How to Get Only First Character Match With Regex
Development Server of Create-React-App Does Not Auto Refresh
How to Display Loading Message When an Iframe Is Loading
Show Questions One At a Time in Quiz Website in HTML
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
Bootstrap 4 Dropdown Menu Not Working
How to Import the Following Function in Another File
Center Content Vertically on Vuetify
How to Access Session Variables and Set Them in JavaScript
Javascript Scrollto Method Does Nothing
How to Extract Data from Json Nested Objects
On Click,Redirect to a New Page and Scroll to a Particular Div on That New Page
Convert/Change JavaScript Document to Jquery
Calculate the Total of Item Quantity into Item Price With Dynamic HTML Input Fields Using Jquery