Arrow Functions in JavaScript

Arrow Functions in JavaScript

What is an Arrow Function?

While Learning JavaScript , you will hear about "arrow" . The 2015 edition of the ECMAScript specification (ES6) added arrow function expressions to the JavaScript language . Arrow functions are a new way to write a function expressions.

Arrow functions and functions are similar. However, there are at least important differences. This will help you decide when it is better to use arrow functions and when functions.

So Arrow Function basically use the arrow syntax to accept arguments like normal function and run into enclosing scope context .

The Function Syntax

To See the Difference between old function syntax and arrow function syntax , i will write a old function syntax and convert into a new arrow function syntax , I'm going to use a very simple function that adds two numbers and returns the result.

function add(a, b) {
    return a + b;
}

The Arrow Function Syntax

The add() function from normal function can be written as an arrow function as follow .

const add = (a, b) => {
    return a + b;
}

const myArrowFunc = () => {/* function body with some code */}

If the Arrow Function That returns a single expression we can write like

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

const  bar = () => "bar"
//function without arguments

In arrow function no need to write return for single return statement.

If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.

   x =>({ y: x })

Immediately invoked arrow functions

JavaScript allows you is to declare and invoke functions at the same time. These functions are called immediately invoked functions To create this type of a function is by wrapping the function with parentheses and adding additional pair of parentheses after the wrapping parentheses.

Normal Function

(function() {
  // some code
})()

Same thing also with arrow functions, create immediately invoked arrow functions

(() => /* some code */)()

(() => {
  /* some code */
})()

(() => { return /* some code */ })()

// Or
(() => {
  return /* some code */
})()

"this" binding

Unlike regular functions, arrow functions don’t have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. Let's see that in a quick example:

name ="Arrow function"
let me = { 
 name: "Regular function", 
 thisInArrow:() => { 
   console.log("Example of " + this.name); //no 'this' binding here 
 }, 
 thisInRegular(){ 
   console.log("Example of " + this.name); //'this' binding works here 
 } 
};
me.thisInArrow(); 
me.thisInRegular();

When to use them

Understanding how to Write Arrow function , it's also important to know when to use them.

1. Iterate over and over again

Arrow Function more use with methods such as map(), filter() and reduce() and more methods , with this code look much cleaner and easy to understand.

Let's see the example with Different method

With Normal Function

  let numbers = [0, 2, 4, 6];

numbers.map(function(num) {
  return num+1;
});

With Arrow Function

let numbers = [0, 2, 4 ,6];

numbers.map(num => num+1);  

let newArray = numbers.filter(number => number >= 3);

2 . Callback Function

Callback functions are very common in JavaScript and reducing them with the arrow syntax

function getUser(name, callBack){
     console.log(`get the ${name}!`);
     callBack();
}
getUser("Victoria", () => console.log("setUser"));

3. Promise chain

fetch(url)
.then(res => res.json())
.then(json => json.data)
.then(data => data.map(into => info.name))

When Not to use

1. Event handlers or Callback with Functions with 'this'

Arrow functions do not have their own scope and this also makes them unsuitable for callback functions which includes 'this'.

<button  id = "btn">Add</button>

const btn = document.getElementById('btn');
              btn.addEventListener('click', () => {
             console.log(this); //refers to window not the button itself
             this.innerHTML = 'Clicked'; //so this won't work
       });

2. Object methods

Let's take counter object:

const counter = {
  count: 0,
   increment: () => this.count++,
  decrement: () => this.count--
};

console.log(counter.increment());

The counter object has two methods: increment() and decrement(). The increment() method returns the current counter value by adding one and the decrement() method returns the value by decrement by one.

However, it returns NaN.

The this.count inside the increment() method is equivalent to the window.count. The window.count is undefined. because window object doesn’t have the count property

Arrow functions are not suitable to be used for object methods when you want to access this.

const counter = {
  count: 0,
   increment() {
       return  this.count++
    },
  decrement() {
         return this.count--
   }

};
console.log(counter.increment());

Now, calling the increment() method will return one as expected.

3. Cannot be Called With new keyword

Arrow functions do not create their own scope when executed. arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.

const Employee = (name) => {
  this.name= name;
  console.log(this);
};

const roger = new Employee('Jon');
// TypeError  Employee  is not a constructor

Conclusion

Hopefully this article helped you learn about JavaScript arrow functions. JavaScript arrow functions are really awesome and have these cool characteristics. Avoid using the arrow function for event handlers, object methods, prototype methods, and functions that use the arguments object. Arrow function doesn’t have its own this value. Thank you for your time. You can connect 👋 with me on , LinkedIn ,GitHub