Function Definition
Let's learn the logic and syntax needed to create our first function!
We'll cover the following...
As we discussed earlier, a function performs a certain task and returns a value. This implies that the function will contain an expression.
The Need for Functions
A function can be used repeatedly, which helps us avoid writing redundant code.
Let’s look at a simple program where we calculate and print the double of an integer:
Press + to interact
let two = 2;let seven = 7;let ten = 10;let doubleOfTwo = two * 2;Js.log(doubleOfTwo); /* 4 */let doubleOfSeven = seven * 2;Js.log(doubleOfSeven); /* 14 */let doubleOfTen = ten * 2;Js.log(doubleOfTen); /* 20 */
The code above is redundantly verbose for no reason. The simple steps are:
- Calculate the double.
- Print its value.