We have a JSON response which can contain null values (e.g. { myValue: null }) – we assign this value to a textbox on a form: (actually, we use JQuery, but this is equivalent
var nullString = null;
document.getElementById('myInput').value = nullString;
If we assign this value to an HTML textbox value, the behaviour seems browser-dependent:
-
Firefox and Chrome both display an empty text box, and when you read ‘value’ back you get null.
-
IE puts the string ‘null’ into the text box, and when you read ‘value’ back, you get the string “null” (i.e. setting ‘value’ and reading it back has modified the data)
(It’s here: http://jsbin.com/uleno/edit if anyone wants to try it)
Which browser is doing the right thing here, or is this undefined behaviour? And is there a cleverer more elegant workaround than doing a lot of (myValue == null ? ” : myValue) stuff?
What’s actually happening is the null object is being stringified, like null.toString(). In an alert() message box, the browser usually interprets the object instead of simply stringifying it, so the result will be different. And, of course, browsers (especially IE) interpret and stringify differently.
For what it’s worth, there is a logic to returning null when a string is expected. Whatever is returning this value probably does so in order to provide a false value for easy conditional testing, while still indicating that the result is empty rather than, eg undefined. DOM methods that return collection objects do the same. Further, while an empty string literal (”) is a false value, an empty String object (new String(”)) is not; and the latter can be created from the former accidentally with further processing. So the “safe” way to prevent the consuming code from accidentally discarding a valid string is to return a string literal or String object in one case, and null in another.