This is indeed returning the value as the documentation states and as you would expect:
function swimWorkout() {
return rand;
}
However, this is not doing what you seem to expect:
<button onclick="swimWorkout();">Find the length </button>
When you click that button, the function is executed and the value is returned. But there is no instruction anywhere regarding what to do with that value. No reason why it would be displayed anywhere, because there's no code to display it.
You've found a way to potentially display something:
document.write(rand);
However, this can be a problematic approach. document.write()
doesn't offer much control over where in the document you'd like to write something. If you have some in-line JavaScript executing as the page loads, it should output right where it is. But anything after that fact probably won't write where you want it to.
Instead, you can use other JavaScript code to select an element and output to it. For example, consider something like this:
myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
function swimWorkout() {
document.getElementById('output').innerText = rand;
}
<button onclick="swimWorkout();">Find the value</button>
<p>The value is: <span id="output"></span></p>
You can further detach your JavaScript from your HTML (also recommended) by binding to a click event rather than writing the function call inline in the HTML:
myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
function swimWorkout() {
document.getElementById('output').innerText = rand;
}
document.getElementById('find-value').addEventListener('click', swimWorkout);
<button id="find-value">Find the value</button>
<p>The value is: <span id="output"></span></p>
Keeping the markup and the logic separate quickly becomes much easier to maintain overall.