0

I want to pass several variables to a function, but my solution is not working. (hope I used the right terms) Here is an example:

function newFunc(color) {

   console.log('my fav color is' + color)

} newFunc('blue', 'black', 'green');

I want to get three console entries.

my fav color is blue
my fav color is black
my fav color is green

What's the correct syntax for this?

user3439585
  • 77
  • 1
  • 8

2 Answers2

0

You have to add all the parameters to your function as well

//all parameters
function newFunc(var1, var2, var3) 
{
   console.log(var1);
   console.log(var2);
   console.log(var3);
} 
//add the parameters when calling the function
newFunc('var1', 'var2', 'var3');

If you have a lot of parameters you could pass an array instead

//add as many parameters as you need
var yourArray = ['var1', 'var2', 'var3', 'var4', 'var5','var6','var7','var8','var9','var10'];
newFunc(yourArray);

//all parameters
function newFunc(parameter) 
{
  //iterate through array
  for( var i = 0; i < parameter.length; i++ )
  {
      //output each element in the array
      console.log(parameter[i]);
  }
}
Master Yoda
  • 4,334
  • 10
  • 43
  • 77
0
function newFunc (name1, name2, name3) {
    ...
}

Name the variables to reflect what data they should contain. You may have an issue with naming the variable 'var' as it's a key word in javascript.

Alternatively, you can reference the arguments variable which is an array which will contain all the passed in arguments, no matter if they were on the function definition or not. But you should use the parameters as much as possible for clarity.

Taplar
  • 24,788
  • 4
  • 22
  • 35