How can JSON encoding be used to prevent errors and security vulnerabilities when passing data from PHP to JavaScript?

JSON encoding can be used to prevent errors and security vulnerabilities when passing data from PHP to JavaScript by ensuring that the data is properly formatted and escaped. This prevents potential security risks such as cross-site scripting attacks. By encoding the data in JSON format, special characters are automatically escaped, reducing the risk of injection attacks.

$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
);

$json_data = json_encode($data);

echo "<script> var jsonData = " . $json_data . "; </script>";