DEV Community

fabriciomsdev
fabriciomsdev

Posted on

Draft: What are the differences between arrow functions and traditional functions?

The Javascript traditional functions have some superpowers instead of simple arrow functions because normal functions follow the Javascript prototype pattern and do not have access to the magic keywords “this” where we can control the function context.

I show below some powers of JS normal functions:

  • Using functions as constructors:

    As an arrow, you will get an error:

      const Person = (name) => {
        this.name = name;
      };
    
      const person = new Person("John");
    

    The error we get:

    Image description

    Using a normal function:

    function  Product(title, price){
      this.title  =  title;
      this.price  =  price;
    }
    
    let  p1  =  new  Product("Pen",100);
    
    console.log(p1);
    

    As a result we will get:

    Image description

  • Having access to "arguments" of the context:

      function myFunc() {
        console.log(arguments);
      }
    
      myFunc(1, 'text', 5, 6); // Logs [1, 'text', 5, 6
    
  • Having their own access to this context:

      const person = {
        value: 'I used normal functions',
        showTheValue: function() {
          setTimeout(function() {
            console.log(this.value); // "this" refers to obj
          }, 1000);
        }
      };
    
      person.showTheValue(); // Logs "I used normal functions"
    

    Using arrow functions:

      const person = {
        value: 'arrow function',
        showTheValue: () => {
          setTimeout(() => {
            console.log(this.value); // "this" does not refer to obj
          }, 1000);
        }
      };
    
      obj.showTheValue(); // Logs undefined or throws an error depending on strict mode
    

Conclusion:

Arrow functions are more concise and straightforward focused only on creating a function that executes a piece of code, normal functions can be used to solve a lot of problems in different ways not only to execute a piece of code.

Top comments (0)