JS: Function (basics)
Here are the basic ways to define a function.
Arrow function
syntax:
(parameters) => expr
and
(parameters) => {statements}
const ff = (x, y) => { return x + y; }; console.log(ff(3, 4)); // 7
Return statement optional. If none, return undefined.
const ff = (x) => { // when no return statement, return undefined console.log("good morn"); }; console.log(ff(3)); // good morn // undefined
curly brackets {} optional if body is a single expression. no return statement.
const ff = (x, y) => x + y; console.log(ff(3, 4)); // 7
The function keyword
Function declaration
function ff(x) { return "Hello " + x; } console.log(ff("Alice")); // Hello Alice
Function expression by the keyword “function”
the function keyword definition can be assigned to a variable.
const ff = function (x) { return "Hello " + x; }; console.log(ff("Alice")); // Hello Alice
Named function expression by the keyword “function”
// name gg here is allowed but ignored const ff = function gg(x) { if (x < 9) return ff(x + 1); else return x; }; console.log(ff(3)); // 9 console.log(typeof ff); // function console.log(typeof gg); // undefined
🟢 tip: it's good idea to always use Arrow Function. Because defining functions by the function (keyword) have very complex rules of: