JavaScript 5 ways to define a function

JavaScript 5 ways to define a function

·

1 min read

JavaScript 5 ways to define a function

  1. Function declaration

     function sum(a, b) {
         return a + b;
     }
    
  2. Function expression

     const sum = function(a, b) {
         return a + b;
     }
    
     const computer = {
         // Function expression
         sum: function(a, b) {
             return a + b;
         }
     };
    
  3. Shorthand method definition

     const computer = {
         // Shorthand method definition
         sum(a, b) {
             return a + b;
         }
     };
    
  4. Arrow function

     const sum = (a, b) => {
         return a + b
     }
    
  5. New function

     const sum = new Function('a', 'b', 'return a + b');
    

My points

  1. Don't use New function because it works like a eval.
  2. Don't use Shorthand method definition because it looks similar with arrow function.
  3. To be consistent, use function expression on both function and method.
  4. If you don't want the this of function itself, use arrow function.