JS: function (keyword)
Create a Function
There are 3 ways to create a function.
The most common way is by the keyword function.
Another common way is by Arrow Function. this is shorter, and simpler.
Another way is by Function Constructor. this is rarely used. only for creating functions at runtime.
Keyword “function”
Function declaration
The syntax is:
function name (parameters) {body_statements}
function ff(x) { return x + 1; } console.log(ff(2)); // 3
// 2 parameters function ff(x, y) { return x + y; } console.log(ff(3, 4)); // 7
Return Statement
In the function body, you can have
0 or more
return expr.
When program reaches the return statement, it'll exit the function, and return the value.
Function without return statement returns the value undefined.
Function expression
the function keyword can be assigned to a variable. when doing so, it is called a function expression.
const ff = function (x) { return "Hello " + x; }; console.log(ff("Alice")); // Hello Alice