2

As demonstrated in the following example:

document.getElementById('test1').value = null;
document.getElementById('test2').value = undefined;
<input id="test1" value="DEFAULT TEXT" />
<input id="test2" value="DEFAULT TEXT" />

An input's value is reset whenever it is set to null, but why doesn't it also reset when it is set to undefined?

How come it sets the value to the string "undefined" instead?

Mystical
  • 2,505
  • 2
  • 24
  • 43

2 Answers2

6

.value is a string and expects a string, so the correct way to empty it would be to use an empty string:

 /*...*/.value = "";

Assigning undefined will cause it to be stringified, which results in "undefined", whereas null cannot be stringified, therefore the spec says, that assigning null to .value will be like using an empty string.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

undefined means a variable has been declared but has not yet been assigned a value.

On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Web Nexus
  • 1,150
  • 9
  • 28
  • `undefined` can also be assigned to a value, as `undefined` is a global variable being underined. – Jonas Wilms Jan 25 '19 at 19:22
  • 1
    Properties and variables can be assigned the value of undefined. It’s what the OP is specifically asking about. But in most situations setting the “value” of an INPUT DOM element to undefined will result in it being cast to a String. The only difference here is the outcome of the cast between null and undefined. I think this answer adds more confusion than it helps. – Cooper Buckingham Jan 27 '19 at 18:32