What is a function?
A function bundles a code block as one unit so that we can use and reuse it without having to rewrite the same code. We’ve already been using functions all over the place. For example, to find the index of an element within an array, we used the find()
function:
var inventory = ["Amulet", "Bananas", "Candles"] print(inventory.find("Bananas"))
Under the hood, the interpreter looks up the code block that is associated with the find
function, executes it with the Bananas
string as input, and then returns the result to us.
In the preceding case, we would print out the result. Note that the print
statement we use in that code is also just a function!
The input data we give to a function is called arguments.
To oversimplify the technical aspects, a function is just a detour that our program makes from its normal path of execution – a sidetrack through another code block.
Defining a function
Let...