Functions
Functions follow the common code pattern of the reserved name, the function name, parameters, and a code block.
function <name> (parameters) { }
function main() {
/*
This is a special type of function.
The main() function is the entry point to code execution
*/
}
The main function is the execution entry point. Other functions and definitions outside the main, but in the file are visible at a Global scope level.
The parameter of a function is the same as that of a TypeScript function. The parameters can be named and have default values.
function hello ({message="Hello World"}) {
printf("Main meessage ->, %s", message)
}
function main () {
hello()
hello({
message: "Goodbye",
unused: "field"
})
}
In this function, we call hello twice. The first time, there is no argument, so the system uses the default argument. The second time, there is a passed object that has a message field. In this case, the "Goodbye" value is presented.
Functions have proper scoping.
function called() {
let x = "local"
printf("%s", x)
// printf("%s", y)
}
function main () {
let x = "global"
let y = "global"
printf("%s", x)
called()
}
In the above example, the function called will print the local variable. However, if we tried to refer to the y variable in the called function, the compiler will give a variable undefined error.
Updated 6 months ago