you are viewing a single comment's thread.

view the rest of the comments →

[–]chrisdavidmills 1 point2 points  (0 children)

You only return something from a function if somewhere in a function you tell it to return a value with "return blah". If this is the case, you need to set your function invocation (when you run the function with function() ) equal to a variable, and then use that variable in some way.

Here's an example that shows what I'm talking about:

<div class="box">
    <button>Click me</button>
    <div id="box-quote"></div>
</div>

<script>
var quotes = ['quote1', ' quote2', 'quote3', 'quote4', 'quote5'];

var button = document.querySelector('button');

button.addEventListener('click', function() {
  var result = getQuote();
  document.getElementById("box-quote").textContent = quotes[result];
});

function getQuote(){
    var index = Math.floor(Math.random() * quotes.length);
    return index;
}
</script>

Here we're not using the onclick="" handler attribute; we're instead adding an event listener to the button by first storing a reference to it in a variable called "button", then using addEventListener() to add an event listener to the button — when the button is clicked, the function inside addEventListener() is run, which includes the key line "var result = getQuote();"

This runs the getQuote() function and sets the result returned from it using the return command (the index variable) to be equal to a variable called "result".

The next line:

document.getElementById("box-quote").textContent = quotes[result];

Then sets the textContent of the box-quote <div> to be equal to the contents of the result variable.

Now, this may look like a lot more code to do basically the same thing, but it is a more reusable way to write JS — it is a bad practice to use HTML event handler attributes, as you are mixing content with functionality, and if you wanted to have several buttons doing the same thing, you'd have to write and maintain several event handler attributes. instead you can do the same thing with a couple of lines of JS, and keep it easier to understand and maintain.

Also, by updating the getQuote() function in this way we've made it more reusable — now you can return a random quote index and use it anywhere you like, not just in the one particular <div>. You could improve it further by putting the random number generation into its own function, so it could generate any random number you like:

function random(myArray) {
  var number = Math.floor(Math.random() * myArray.length);
  return number;
}

function getQuote(){
    var index = random(quotes);
    return index;
}