What are the implications of assigning JavaScript code to variables in PHP templates and how can potential issues be mitigated?

Assigning JavaScript code to variables in PHP templates can lead to potential security vulnerabilities such as Cross-Site Scripting (XSS) attacks if the JavaScript code is not properly sanitized. To mitigate this issue, it is important to properly escape the JavaScript code before outputting it in the HTML.

<?php
$javascriptCode = "<script>alert('Hello, world!');</script>";
$escapedJavascriptCode = htmlspecialchars($javascriptCode, ENT_QUOTES, 'UTF-8');
echo "<script>{$escapedJavascriptCode}</script>";
?>