Creating Functions In Javascript
The different ways to define a function in JavaScript
- 1. Declaration Function
- 2. Expression Function
- 3. Arrow Function
- 4. Generator Function
- 5. Async Function
- 6. Constructor Function (AVOID)
- 7. Exported Function
- 8. Object Property Function
- 9. Object Dynamic Property Function
- 10. Object Property Getter/Setter Function
- 11. Object Dynamic Property Getter/Setter Function
- 12. Class Method Function
- 13. Class Property Function
- 14. Class Private Function
So you want to create a function in JavaScript?
You. Have. Options:
1. Declaration Function
function sum(a, b) { return a + b; }
2. Expression Function
// Can be named: (function sum(a, b) { return a + b; }); // Or anonymous (AVOID): (function(a, b) { return a + b; }); // Or assigned to a variable const sum = function sum(a, b) { return a + b; })
3. Arrow Function
// Regular: (a, b) => { return a + b }; // Single argument, one line return: name => name.split(' ') // Multi arguments, one line return: (a, b) => a + b // Single argument, full body: name => { return name.split(' '); }
4. Generator Function
function *sum(a, b) { yield a + b; }
5. Async Function
async function sum(a, b) { return await a + b; }
6. Constructor Function (AVOID)
new Function('a', 'b', 'return a + b;');
7. Exported Function
// Default exports export default function(a, b) { return a + b; }; // Named exports export function sum(a, b) { return a + b; };
8. Object Property Function
// Regular: const object = { sum: function(a, b) { return a + b; }, }; // Shorthand: const object = { sum(a, b) { return a + b; }, };
9. Object Dynamic Property Function
const functionName = "sum"; const object = { [functionName]: function(a, b) { return a + b; }, };
10. Object Property Getter/Setter Function
// Regular: const object = { get answer { return 42; }, set answer(value) { /* do something with value */ }, }; // With defineProperty const obj = {}; Object.defineProperty(obj, "answer", { get() { return 42; }, set(value) { /* do something with value */ }, });
11. Object Dynamic Property Getter/Setter Function
const functionName = "answer"; const object = { get [functionName]() { return 42; }, set [functionName](value) { /* do something with value */ }, };
12. Class Method Function
class Compute { // Regular: sum(a, b) { return a + b; } } class Compute { // Static: static sum(a, b) { return a + b; }; }
13. Class Property Function
class Compute { // Regular: sum = function (a, b) { return a + b; }; } class Compute { // Static: static sum = function(a, b) { return a + b; }; }
14. Class Private Function
class Compute { // Regular: #sum(a, b) { return a + b; } // Static: static #sum(a, b) { return a + b; } }
I tried to keep the list to only the uniquely different ways to create a function. If you start thinking about combining some of these ways there would be a lot more options. |
Did I miss anything? Let me know.