Functions
Use functions to modularize shared logic such as data extraction and generation.
Definition
Use the func
keyword to define either single or multi-line functions.
Any valid expression can be used on the right-hand side of the ->
symbol.
- Knot
- TypeScript
knot
func increment(value: integer) -> value + 1;func addAndDouble(lhs: integer, rhs: integer) -> {let total = lhs + rhs;total * 2;};
knot
func increment(value: integer) -> value + 1;func addAndDouble(lhs: integer, rhs: integer) -> {let total = lhs + rhs;total * 2;};
tsx
function increment(value: number) {return value + 1;}function addAndDouble(lhs: number, rhs: number) {let total = lhs + rhs;return total * 2;}
tsx
function increment(value: number) {return value + 1;}function addAndDouble(lhs: number, rhs: number) {let total = lhs + rhs;return total * 2;}
Empty Arguments
If your function does not take any arguments you can drop the parentheses as well.
- Knot
- TypeScript
knot
func stringFactory -> "string";const result = stringFactory();
knot
func stringFactory -> "string";const result = stringFactory();
tsx
function stringFactory() {return "string";}const result = stringFactory();
tsx
function stringFactory() {return "string";}const result = stringFactory();
Default Arguments
You can make your arguments optional by passing default values. However, if you add a default value you must also add default values for all subsequent arguments.
- Knot
- TypeScript
knot
func add(lhs: integer, rhs = 10) -> lhs + rhs;const result = add(5, 2);
knot
func add(lhs: integer, rhs = 10) -> lhs + rhs;const result = add(5, 2);
tsx
function add(lhs: number, rhs = 10) {return lhs + rhs;}const result = add(5, 2);
tsx
function add(lhs: number, rhs = 10) {return lhs + rhs;}const result = add(5, 2);