# Cutting the Boilerplate with Arrow Functions

You have encountered this piece of code multiple times at different places, in tutorials, GitHub:

```javascript
const add = (a, b) => a + b;
```

This looks weird and alien at first, but once you understand this, it becomes a default for you to use in code.

## What Are Arrow Functions?

**Arrow functions** are just a shorter way to write functions. That is the whole story. They behave similarly to regular functions in most cases; their syntax requires less typing and looks natural.

This is how a Function looks:

```javascript
function greet(name) {
  return "Hello, " + name;
}

console.log(greet("User")); // "Hello, User"
```

The same function can be written using arrow functions:

```javascript
const greet = (name) => {
  return "Hello, " + name;
};

console.log(greet("User")); // "Hello, User"
```

They produce the same output; the difference lies in the structure of the functions. The `function` keyword is dropped, and an arrow `=>` is added between the parameter and the body.

### Basic Syntax Breakdown

![](https://cdn.hashnode.com/uploads/covers/678b775e773554ab7117f20a/beb86d29-7dcb-4a53-85bb-0488a8568476.png align="right")

![](https://cdn.hashnode.com/uploads/covers/678b775e773554ab7117f20a/2f0750df-9c1e-4902-b848-c825d4ed021d.png align="center")

* * *

## Arrow Function with Single Parameter

When arrow functions take a single parameter, the parentheses can be dropped.

```javascript
// With parentheses, always valid
const shout = (word) => {
  return word.toUpperCase();
};

// Without parentheses, also valid with a single parameter
const shout = word => {
  return word.toUpperCase();
};

console.log(shout("hello")); // "HELLO"
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">It is a good practice to use parentheses in your code to avoid confusion.</div>
</div>

* * *

## Arrow Function with Multiple Parameters

When you have two or more parameters, the parentheses are not optional. They are required.

```javascript
// Two parameters
const add = (a, b) => {
  return a + b;
};

console.log(add(3, 5));  // 8

// Three parameters
const fullName = (first, middle, last) => {
  return first + " " + middle + " " + last;
};

console.log(fullName("Amar", "Akbar", "Anthony")); // "Amar Akbar Anthony"
```

When there are no parameters, parentheses are still needed:

```javascript
const greetWorld = () => {
  return "Hello, World!";
};

console.log(greetWorld()); // "Hello, World!"
```

* * *

## Implicit Return vs Explicit Return

An **explicit return** means you write the `return` keyword yourself, inside curly braces.

```javascript
const square = (n) => {
  return n * n; // explicit return
};
```

An **implicit return** means the curly braces and the `return` keywords are dropped, and the arrow function will automatically return whatever expression follows the arrow:

```javascript
const square = (n) => n * n; // implicit return

console.log(square(4)); // 16
console.log(square(9)); // 81
```

![](https://cdn.hashnode.com/uploads/covers/678b775e773554ab7117f20a/0b316815-44b7-417e-997f-c6b363555a7e.png align="center")

Here are some examples of the usage of these return types:

```javascript
// Implicit

// Multiply two numbers
const multiply = (a, b) => a * b;
console.log(multiply(6, 7));  // 42

// Check if a number is even
const isEven = (n) => n % 2 === 0;
console.log(isEven(4));  // true
console.log(isEven(7));  // false

// Build a greeting string
const greet = (name) => `Hey, ${name}`;
console.log(greet("User"));  // "Hey, User"
```

```javascript
// explicit

// Multi line body needs curly braces and explicit return
const describe = (n) => {
  const type = n % 2 === 0 ? "even" : "odd";
  return `${n} is ${type}`;
};

console.log(describe(7));   // "7 is odd"
console.log(describe(12));  // "12 is even"
```

If curly braces are used, but the return keyword is not used, then the function would return `undefined`

```javascript
const broken = (n) => { n * 2 }; // no return
console.log(broken(5)); // undefined
```

* * *

## Arrow Functions vs Normal Functions

| Feature | Normal function | Arrow function |
| --- | --- | --- |
| Syntax | function keyword required | uses `=>`, no function keyword |
| Can be named | yes | only through the variable it is stored in |
| Hoisting | declarations are hoisted to the top of the scope | not hoisted (must be defined before use) |
| `this` keyword | has its own `this` | inherits `this` from the surrounding scope |
| `arguments` object | Has its own `arguments` | No `arguments` (Use `...args` instead) |
| Use as constructor | Yes, with `new` | No, throws an error |
| Best used for | methods, constructors, complex logic | callbacks, array methods, short utilities |

### Hoisting of Arrow Function

Normal function declarations get hoisted to the top of their scope, which means you can call them before you define them in the file and it still works. Arrow functions stored in variables do not behave that way:

```javascript
 // Normal function: this works 
console.log(sayHi()); // "Hi" -- called before definition

function sayHi() {
  return "Hi";
}

// Arrow function: this throws a ReferenceError
console.log(greet()); // ReferenceError: Cannot access before initialization

const greet = () => "Hi";
```

* * *

## Arrow Function Importance

The arrow functions finds its real importance in array methods. Array Methods take a function as an argument, and make the code readable when used with arrow functions.

For example, there is an array of product prices and 10% discount is applied to it:

```javascript
const prices = [29.99, 49.99, 9.99, 89.99];

// Using a normal function inside map
const discounted = prices.map(function(price) {
  return price * 0.9;
});

// Using arrow function
const discounted = prices.map((price) => price * 0.9);

console.log(discounted);
// [26.991, 44.991, 8.991, 80.991]
```

The arrow function makes things fit in a single line.

* * *

**REFERENCES:**

*   [MDN: Arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
    
*   [javascript.info](http://javascript.info)[: Arrow functions, the basics](https://javascript.info/arrow-functions-basics)
