@AbraCadaver is right, you are missing quotes when you are assigning the value to the variable fn.
<?php
$dir = "folder/*";
foreach(glob($dir) as $file) {
$result .= $file . '</br>';
}
?>
<script>
var fn = "<?php echo $result; ?>"; // <- Error was here
console.log(fn);
</script>
Note, that generating JavaScript by joining strings can be tricky and buggy, sometimes better option is passing your data as a JSON object into JS and then working with it with JS:
<?php
$dir = "folder/*";
$arr = [];
foreach (glob($dir) as $file) {
$arr[] = $file;
}
$jsonObj = json_encode($arr);
?>
...
<script>
var fn = <?php echo $jsonObj; ?>; // <- in this case DO NOT wrap JSON object with quotes!
fn.forEach(myFunction);
function myFunction(item, index) {
console.log(index, item);
}
</script>