- · The function statement
- · The Function() constructor
- · The function literal
Let’s create a function called add to demonstrate these three approaches. The purpose of this function is to take the two passed arguments, add the arguments, and return the result.
xyzzy = add; alert(xyzzy(2,2))
will produce the same results as:
Functions with a variable number of arguments
Each of the function examples we’ve discussed so far has had a fixed number of arguments that were referenced by using the argument’s name. While this works, the problem is that often the number of arguments can be varied. Using the add function from Listing A, the result of add(2,2) is the same as add(2,2,2), which can lead to unexpected results. You can handle a variable number of arguments to a function through the arguments object, which accomplishes this task through the length property and the arguments collection, as shown in Listing E.
I have a button that says “Recursion – adj. see recursion,” which pretty much sums up the meaning of recursion. Recursion happens when a function either directly or indirectly calls itself. Recursion can be dangerous, because care must be taken to provide an exit to the recursion, but it is a useful way to handle some problems. An example of this is the mathematical function factorial (!), which is the product of all positive integers from 1 to any given number. So, 5! is equal to 120 and 6! is equal to 720, and so on. Listing G shows a recursive implementation of factorial.