0

I have an array with functions: var ranArray = [funct1(), funct2()] and the functions themselves:

function funct1() {
    document.write("hello");
};
function funct2() {
    document.write("hi");
};

I am trying to make it so that whenever a button is pressed, either funct1 or funct2 is executed. However, without me even pressing the button, on the page I see my button and "hellohi". Here is the function for the randomization:

function getFunctions() {
    return ranArray[Math.floor(Math.random * ranArray.length)];
}; 

and here is the HTML:

<button type="button" name="ranButton" id="ranButton" onclick="getFunctions();">Random Button</button>
0

2 Answers 2

2

Firstly you need to store the function references ([funct1, funct2]), the () will immediately call the functions. Next you can use .call() to call the function, or more simply add () at the end of ranArray[Math.floor(Math.random() * ranArray.length)] as @jfriend00 mentioned. Also note that Math.random needs to be Math.random().

var ranArray = [funct1, funct2];

  function funct1() {
    document.write("hello");
  };
  function funct2() {
    document.write("hi");
  };

  function getFunctions() { // Note you don't really need a 'return' here
    return ranArray[Math.floor(Math.random() * ranArray.length)]();
  }; 

Demo


Also the use of document.write() here is overwriting the DOM. So I don't recommend it, rather you may want to place this content inside a element. If you have some element of the id #foo you could instead set the text of that DOM element:

document.getElementById("foo").textContent = "...";

Demo 2

Sign up to request clarification or add additional context in comments.

5 Comments

There's no reason for .call() here. You can just use return ranArray[Math.floor(Math.random() * ranArray.length)]();
@jfriend00 Really? I would of not expected that to work. I'll edit it in, thanks for that.
The result of indexing into your array is a function reference so just adding a () on the end will call that function reference.
Thanks guys... I'm new at JS. :/
@heptagonalhippo No problem, don't worry about it. It's quite common to confuse function references and function calls. Note you can accept answers with the green checkmark to the left.
1

Your array declaration is actually calling funct1 and funct2 and trying to store the return values in the array. What you want is an array of functions. Remove the parentheses so the functions themselves are stored in the array rather than the return values. It should look like this:

var ranArray = [funct1, funct2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.