More Functions
Functions become much more powerful and flexible when they are designed to take input data or return soume output data.
Parameters
Here is a function that doubles a value and logs it to the console:
You can probably guess that calling doubleValue()
will log 20
to the console. However, this function is very limited because it always doubles the hard-coded number 10
.
To make it more flexible, we will include a parameter in its definition. Then, when the new function is called, a value can be passed as an argument and used as a local variable inside the function. In the example below, x
is the parameter.
See the Pen Function Parameters (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.
Returning Values
The doubleValue()
function would be much more useful if we could use the result elsewhere in the code instead of just logging it to the console. This can be accomplished using the return
keyword. The returned value can then be assigned to a variable and used outside of the function.
See the Pen Function Parameters (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.
Here is a more sophisticated example with two functions: one that converts Fahrenheit to Celsius and another that does the reverse.
See the Pen Function Return Temperature (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.