'InnerHTML for null vs undefined

Consider this snippet

const div = document.createElement('div');
div.innerHTML = null; // 1
console.log(`After setting null: "${div.innerHTML}"`);
div.innerHTML = undefined; // 2
console.log(`After setting undefined: "${div.innerHTML}"`);

Why doesn't the first snippet of innerHTML yield "null"? I expected the value to be a result of innerHTML = value to be same as String(value) as it expects a DOMString? String(null) yields "null".

MDN also mentions the ToString approach which too returns "null". The only thing that might hint at this special behavior is this snippet from the page on DOMString

Certain Web APIs accepting a DOMString have an additional legacy behavior, where passing null stringifies to the empty string instead of the usual "null".

Are there any definitive places (spec or otherwise) where such behavior can be confirmed from?



Solution 1:[1]

Yes, there is a spec: https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin

innerHTML has the "IDL extended attribute" LegacyNullToEmptyString which describes this behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mercator