# Arrow Functions in JavaScript

Before knowing what arrow functions does and why it was introduced. Let's understand what function expression is.

### Function Expression

It means to use `function` keyword and define a function inside an expression. In simple words, previously folk use to write and assign function to variable as below,

```javascript
const ctc = function (base, variable) { return base +  variable; };

console.log(ctc(30000, 40000));
```

## Arrow Functions

So, Arrow Functions are used to create a arrow function expression. An alternate to traditional approach mentioned above.

Example

```javascript
const ctc = (base, variable) => base + variable;

console.log(ctc(30000, 40000)); 
```

But, it has it's own behavior

*   They don't have their own binding and should not be used as methods.
    
*   We cannot use them as constructor
    
*   It cannot use yield within their body and cannot be used as generators.
    

### No own bindings to `this`, `arguments`, or `super`

Regular functions are dynamic. So the value of `this` depends on **how** the function is called. If an object calls a method, `this` refers to that object.

Arrow functions are lexical. They do not create their own `this` context. Instead, they inherit `this` from the surrounding scope where they were defined (like looking up to their parent block).

Imagine the Great Hall of Winterfell (the **Parent Scope**). Lord Eddard Stark is organizing his forces. He sends two warriors south to the Red Keep (the **Object**) to serve the Crown.

*   **The Sellsword / Regular Function (Bronn):** Bronn's loyalty is *dynamic*. It depends entirely on who is currently paying him right now. When Cersei Lannister at the Red Keep issues a command and asks, "Who do you fight for?", Bronn looks around at his current employer and says, *"I fight for House Lannister."* (`this` = the object that called the method).
    
*   **The Loyal Bannerman / Arrow Function (Arya Stark):** Arya's loyalty is *lexical*. Her allegiance was permanently forged in Winterfell the moment she was born. Even though she is physically standing in the Red Keep, and Cersei is the one issuing the command, Arya completely ignores her current surroundings. When asked, "Who do you fight for?", she looks back to her origins and says, *"I fight for House Stark."* (`this` = the parent scope where she was created).
    

Example

```javascript
const winterfell = {
  houseName: "Stark",

  sendWarriorsSouth: function() {

    const redKeep = {
      houseName: "Lannister",
      
      bronn: function() {
        console.log(`Bronn says: I fight for House ${this.houseName}`);
      },

      arya: () => {
        console.log(`Arya says: I fight for House ${this.houseName}`);
      }
    };

    redKeep.bronn(); 
    redKeep.arya();  
  }
};

winterfell.sendWarriorsSouth();

// Output:
// Bronn says: I fight for House Lannister
// Arya says: I fight for House Stark
```

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/7a089054-46c3-4c39-b1d2-821ec56857da.png align="left")

Note: Generally arrow function are not use in methods, because object methods usually need to talk to the object they live inside, and arrow functions are physically incapable of doing that.

### Cannot be used as constructors

In JavaScript, regular functions can be used to create blueprints for new objects using the `new` keyword. When you call `new RegularFunction()`, JavaScript creates a brand new object, binds `this` to that new object, and links it to the function's prototype.

Arrow functions were designed to be lightweight and fast. To save memory and execution time, JavaScript engines completely removed the `.prototype` property from arrow functions. Without a prototype, and without the ability to bind a new `this`, they simply cannot construct objects.

Regular Function:

```javascript

function Car(model) {
  this.model = model;
}
const myCar = new Car("Honda"); 
console.log(myCar.model);
```

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/37aa2d94-bd25-45a0-8148-e3ca6641441c.png align="left")

Arrow Function

```javascript

const Bike = (model) => {
  this.model = model;
};


const myBike = new Bike("Yamaha"); 
```

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/6200ccb6-81e5-408b-ae5e-178f13e61ff4.png align="left")

### Cannot use `yield`

A generator function (`function*`) is a special type of function that can pause its execution, hand a value back to the caller using the `yield` keyword, and then resume later exactly where it left off. It acts like a state machine.

Example

```javascript
function* snackMachine() {
  yield "Chips";
  yield "Chocolate";
  return "Empty";
}

const machine = snackMachine();
console.log(machine.next().value); // Output: "Chips"
console.log(machine.next().value); // Output: "Chocolate"
```

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/99810c88-fa49-449e-a3e0-c7a09bb1f3bc.png align="left")

Arrow functions were strictly designed to be single-purpose, run-to-completion expressions. The designers of JavaScript (the TC39 committee) decided that combining the complex, state-pausing mechanics of generators with the ultra-concise syntax of arrow functions would make the language too confusing and harder to parse.

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/68bd4f5d-e908-4a8f-82da-606dcc49e88c.png align="left")

Now, when you are writing modern web apps, like subscribing to an observable stream of user data or handling a button click event in a component you just use an arrow function.

> *"We cannot solve our problems with the same thinking we used when we created them."*
> 
> — **Albert Einstein**

### **Let's Connect! 🚀**

I’m currently deep-diving into the **JavaScript**, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!

*   **Connect on LinkedIn:** [**Satpalsinh's Profile**](https://www.linkedin.com/in/satpalsinhrana)
    
*   **Follow my Blog:** [**blogs.satpal.cloud**](http://blogs.satpal.cloud)
    

**Keep coding and keep building.**
