What are the potential pitfalls of passing variables from PHP to JavaScript?

Passing variables from PHP to JavaScript can potentially lead to security vulnerabilities such as Cross-Site Scripting (XSS) attacks if the input is not properly sanitized. To mitigate this risk, it is important to properly escape the variables before outputting them in JavaScript. One way to do this is by using the json_encode function in PHP, which helps to ensure that the data is safely transferred between the two languages.

<?php
// Define a PHP variable
$data = "Hello, world!";

// Encode the variable using json_encode
$encoded_data = json_encode($data);
?>

<script>
// Pass the encoded PHP variable to JavaScript
var js_data = <?php echo $encoded_data; ?>;

// Use the JavaScript variable
console.log(js_data);
</script>