Passing image from backend into javascript Kirby

Hi, I am passing an image into javascript using Kirby, I get no errors so I have no idea why this isn’t working. There is an image in the page files, as there is only one for this page, I am attempting to load this one in.

  var heroImage = <?php echo json_encode($heroImage = $page->image()) ? $heroImage->url() : ''; ?>;
  img.src = heroImage;

I found a different method which worked, but its Potentially Unsemantic Markup.

  var div = document.getElementById("dom-target");
  var myData = div.textContent;
  img.src = myData;

 <div id="dom-target" style="display: none;">
    <?= ($f = $page->image()) ? $f->url() : ''; ?>
 </div>