How to use a PHP variable in JavaScript?

To use a PHP variable in JavaScript, echo it into a script tag as a JavaScript variable.

Like so:

  <?php $myPhpVar = 'my PHP var'; ?>
  <script>
    <?php echo "var myJsVar = '$myPhpVar';"; ?>
    console.log(myJsVar); // my PHP var
  </script>

This code prints my PHP var to the JavaScript console.