JavaScript 5 ways to define a function
Function declaration
function sum(a, b) { return a + b; }
Function expression
const sum = function(a, b) { return a + b; }
const computer = { // Function expression sum: function(a, b) { return a + b; } };
Shorthand method definition
const computer = { // Shorthand method definition sum(a, b) { return a + b; } };
Arrow function
const sum = (a, b) => { return a + b }
New function
const sum = new Function('a', 'b', 'return a + b');
My points
- Don't use
New function
because it works like aeval
. - Don't use
Shorthand method definition
because it looks similar witharrow function
. - To be consistent, use
function expression
on both function and method. - If you don't want the
this
of function itself, usearrow function
.