What potential issues can arise when dynamically generating JavaScript code within PHP functions?

One potential issue that can arise when dynamically generating JavaScript code within PHP functions is the risk of syntax errors or unintended behavior due to improper escaping of characters. To solve this, it is essential to properly escape special characters like quotes and newlines to ensure the generated JavaScript code is valid.

<?php
function generateDynamicJS() {
    $dynamicValue = "Hello, world!";
    
    // Escape special characters in the dynamic value
    $escapedDynamicValue = json_encode($dynamicValue);
    
    // Output JavaScript code with properly escaped dynamic value
    echo "<script>";
    echo "var dynamicValue = " . $escapedDynamicValue . ";";
    echo "</script>";
}
generateDynamicJS();
?>