0

What I am trying to do is set a variable specified in a function to something, see below if that doesn't really make sense.

function getRandomFromArray(arrayName,storeVariable)
{
storeVariable = arrayName[Math.floor(Math.random() * arrayName.length)]
}

var petTypeArray = ['Cat','Dog','Ferret','Spider','Companion Bot'];

getRandomFromArray(petTypeArray,petType)

For example, set petType to a random string in petTypeArray. Am I doing it right? Am I able to do it like this?

1
  • 3
    Why not just use a regular return value and variable assignment? Commented Apr 6, 2014 at 7:43

3 Answers 3

2

You could use the return value of the function:

function getRandomFromArray(arrayName) {
    return Math.floor(Math.random() * arrayName.length);
}

var petTypeArray = ['Cat', 'Dog', 'Ferret', 'Spider', 'Companion Bot'];
var randomElement = getRandomFromArray(petTypeArray);

This makes the code more readable. Modifying parameter values inside the function is possible but it doesn't work with primitive types such as strings and integers. You can only modify the properties of some complex object.

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

1 Comment

Thanks heaps. Really should of thought of that.
1

No. You are not doing in correctly. The reason is, the variables are just references to data. They don't mean anything themselves. So, when you say

storeVariable = Math.floor(Math.random() * arrayName.length)

you are making storeVariable refer to a new value. Thats it. You are not making changes to storeVariable. That is why it will not work. Instead, you can return the value from the function like this

function getRandomFromArray(arrayName)
{
    return arrayName[Math.floor(Math.random() * arrayName.length)];
}

and make some other variable refer the returned data, like this

var randomData = getRandomFromArray(myArray);

Comments

1

In JavaScript, all parameters are passed by value.

This means that storeVariable receives a COPY of the value that you call with. That local copy can change but it can't influence the original.

(Yes, ALL parameters are passed by value. For those about to downvote me, objects are passed by value. That value just happens to be a reference to the original object.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.