How do I pass variables and data from PHP to JavaScript?

I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?

I have code that looks like this:

     $val = $myService->getValue(); // Makes an API and database call

I have JavaScript code that needs val and looks along the lines of:

    myPlugin.start($val); // I tried this, but it didn't work
    <?php myPlugin.start($val); ?> // This didn't work either
    myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails