JS: Function (basics)
Here are the basic ways to define a function.
Arrow function
const ff = (x, y) => { return x + y; }; console.log(ff(3, 4)); // 7
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
const ff = function (x) { return "Hello " + x; }; console.log(ff("Alice")); // Hello Alice
Named function expression
// 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: