How to pass a php variable to js within a template?

If you would want to pass the whole wp query you could pack it up in arrays, then json encode it and just write it out in a tag.

<?php my_posts = array();
              while ( have_posts() ) : the_post(); ?>
                    <?php
                    $properties = array(
                        'title' => get_the_title(),
                        'link' => get_the_permalink()
                    );
                    $my_posts[] = $properties; ?>
            <?php endwhile; wp_reset_query(); ?>

    <script>
                var posts = <?php echo json_encode($my_posts); ?>; 
               console.log(posts);
</script>

Of course this might not be the best idea securitywise.