What is a recommended approach for setting JS variables with PHP values in a WordPress environment?

In a WordPress environment, a recommended approach for setting JS variables with PHP values is to localize the script using the wp_localize_script() function. This function allows you to pass PHP values to your JavaScript file, making it easy to access dynamic data in your scripts.

// Enqueue your script
function my_custom_script() {
    wp_enqueue_script( 'my-script', 'path/to/my-script.js', array( 'jquery' ), '1.0', true );

    // Pass PHP values to the script
    wp_localize_script( 'my-script', 'my_script_vars', array(
        'variable1' => 'value1',
        'variable2' => 'value2',
    ) );
}
add_action( 'wp_enqueue_scripts', 'my_custom_script' );