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