Detailed answer
Escape markup characters when they must appear as text.
Character references let an HTML lesson show tags without turning them into elements. Use code for a short example and pre with code when whitespace matters. Escaping markup is separate from validating or sanitizing arbitrary user content.
Example
<p>The <article> element.</p>
<p>Research & development.</p>
Understanding the behavior
A literal less-than sign can begin markup, so encode it when the intention is to show source code. Encoding text is different from sanitizing HTML that you intend to allow. A code element changes meaning and presentation, but does not escape its contents.
Practical implementation notes
For text inserted by JavaScript, assign textContent rather than concatenating untrusted strings into innerHTML. Check that the example is displayed as text and creates no extra elements in the DOM.
How to check it
Compare a literal tag with an escaped one inside code and inspect the rendered text.
Expected result
The escaped version visibly shows angle brackets instead of creating an element.
Watch out: Avoid inserting untrusted text through innerHTML.
Read the reference ↗