A CDATA section within a script tag is used to include data within a script element that should not be parsed as JavaScript. CDATA stands for Character Data, and it allows you to include characters that might otherwise be interpreted as HTML or XML markup.
Without a CDATA section, the browser might interpret the reserved characters as actual JavaScript or HTML code, which could result in a syntax error or unexpected display of HTML content on the page.
In general, CDATA sections are not necessary for most JavaScript code, but there are certain cases where they are useful. For example, if you need to include a string that contains characters that are reserved in JavaScript or HTML, such as the less-than (<) or greater-than (>) signs, you can wrap the string in a CDATA section to prevent the browser from interpreting those characters as markup.
Syntax for CDATA:
<![CDATA[ ... ]]>
Example 1: The string message contains HTML tags (<em> and </em>). By wrapping the string in a CDATA section, the browser will treat the contents of the string as raw data and not as JavaScript or HTML code. As a result, the HTML tags in the string will not be interpreted as actual HTML markup, and the string will be displayed as intended when the script is executed.
HTML
< script > /* <![CDATA[ */ var message = "This is a message with < and > symbols"; /* ]]> */ console.log(message); </ script > |
Output:
This is a message with embedded HTML
Example 2: The string message contains the < and > symbols, which are reserved characters in both JavaScript and HTML. By wrapping the string in a CDATA section, the browser will treat the contents of the string as raw data and not as JavaScript or HTML code. As a result, the < and > symbols in the string will not be interpreted as actual JavaScript or HTML markup, and the string will be displayed as intended when the script is executed.
HTML
< script > /* <![CDATA[ */ var message = "This is a message with < and > symbols"; /* ]]> */ console.log(message); </ script > |
Output:
This is a message with < and > symbols
Example 3: In this example, the string message contains the ‘ and \ symbols, which are reserved characters in JavaScript. By wrapping the string in a CDATA section, the browser will treat the contents of the string as raw data and not as JavaScript code. As a result, the ‘ and \ symbols in the string will not be interpreted as actual JavaScript code, and the string will be displayed as intended when the script is executed.
HTML
< script > /* <![CDATA[ */ var message = "This is a message with ' and \ symbols"; /* ]]> */ console.log(message); </ script > |
Output:
This is a message with ' and \ symbols