What are some best practices for escaping characters in PHP when generating JavaScript code?

When generating JavaScript code in PHP, it is important to properly escape characters to prevent syntax errors or security vulnerabilities. One common method is to use the `json_encode()` function in PHP, which will properly escape special characters and format the data as a valid JavaScript object or array.

$data = "Hello, world! 'Quotes' and \"double quotes\" are special characters.";
$escaped_data = json_encode($data);
echo "<script> var jsData = " . $escaped_data . "; </script>";