Javascript Student - Returning an array via index # - Parameter question

Viewed 90

Image

Please see attached image for instructions. I'm currently a student studying for web development, I've noticed parameters being called arguments when I was under the impression, you create the argument outside of the bracket. Is this true?

How do I got about selecting parameters for a function? For example, I cannot get a console.log when I add parameters into this function in the image.

I'm also having trouble returning a specific "flavor of ice cream" with an index number. When, I attempt to do a console.log, it returns the flavor from the preset array above in the assignment.

Any tips? I need a better understanding of this going forward. Thank you for your help.

function getFlavorByIndex(){

    console.log(originalFlavors[2])

}



2 Answers

From the MDN Web Docs (emphasis added):

Note the difference between parameters and arguments:

  • Function parameters are the names listed in the function's definition.
  • Function arguments are the real values passed to the function.

So it looks like you need something like this:

function getFlavorByIndex(flavorsArray, index) {
    return flavoursArray[index];
}

Where flavorsArray and index are the two parameters.

If you wanted to test the getFlavorByIndex function you would call it using something like:

let originalFlavors = ["Apple", "Banana", "Carrot"];
console.log(getFlavorByIndex(originalFlavors, 1)); 

In the above call, which would output "Banana" to the console originalFlavors and 1 are the arguments to the getFlavorByIndex function and result of that call is the argument to the console.log method.

You might also want to read the MDN Web Docs for return:

The return statement ends function execution and specifies a value to be returned to the function caller.

Since you are new to programming I'll try to simplify it as much as posible: first you define a function (give it a name, indicate the required parameters, and what it does to them):

function getFlavorByIndex(originalFlavors, anyIndex){

  console.log(originalFlavors[anyIndex])

} 

Then you call/execute the funcion, with actual values:

 getFlavorByIndex(['Apple','Banana','Coconut', 'Donut'], 2);
//prints 'Coconut'
Related