Generating a random link through Javascript/HTML
<p>I am trying to create a script that allows me to display a hyperlink that redirects the user to a random url selected out of four sites. So far I have created an array for the sites, and a function that attempts to generate the random url. For my purpose it is important for the output ("Click to go to a random site") is not a button, but a simple (clickable) string.</p>

<p>When running the code I get a reference error "link is not defined (on line 18)". I thought that I had defined link in the code with <code>var link = 'http://' + links[randIdx];</code>, so I am not entirely sure why I am getting this error and how to fix it. </p>

<p>Anyone that could take a look at my code to see where I have made a mistake and how I could fix it?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="javascript:openSite()"&gt;Click to go to a random site&lt;/a&gt;
&lt;script&gt;
function openSite() {
var links = [
              "google.com",
              "youtube.com",
              "reddit.com",
              "apple.com"]

            openSite = function() {
              // get a random number between 0 and the number of links
              var randIdx = Math.random() * links.length;
              // round it, so it can be used as array index
              randIdx = parseInt(randIdx, 10);
              // construct the link to be opened
              var link = 'http://' + links[randIdx];
              };
              
    return link;
    
    document.getElementById("link").innerHTML = openSite();
}
&lt;/script&gt;</code></pre>
</div>
</div>
</p>