Best practice to populate a JavaScript array

Hi there,

on my page, I need to read the urls from different video files and feed them into an array to be later used in JavaScript.

At the moment I put a script tag like this in my html, so the videoSources var can later be used in JavaScript:

    var videoSources = [
      <?php foreach($frontPage->children()->visible() as $frontPageDocument): ?>
        "<?= $frontPageDocument->imgVideo()->toFile()->url() ?>",
      <?php endforeach ?>

While this works, this does not seem like a very elegant solution. It creates on extra (empty) array entry. I am also not sure, if this needs a loop at all. Is there maybe a kirby-way to merge collection fields to one long string?
Lastly: Is the way of putting this in a script tag the right way to go?

Thanks for you help!

$urls = [];
foreach($frontPage->children()->visible() as $frontPageDocument) {
  if ($video =  $frontPageDocument->imgVideo()->toFile()) {
    $urls[] = $video->url();
$json =json_encode($urls);
var videoSources = <?= $json ?>

Thank you, that is much cleaner than my approach.