ES6 Arrow Functions

The ES6 arrow functions in Javascript is nothing but a brand new syntax to creation Javascript functions. It has got some syntax differences and also with the scope of the variables in arrow functions. Today we will look into the ES6 arrow functions, its syntax and how it differs from the normal javascript functions.

A normal function in Javascript can be defined using the function keyword whereas for the arrow functions, we will need to use the arrow symbol which is the combination of equal to (=) and greater than (>) symbol. Also for the arrow functions it is mandatory that it needs to be assigned to a variable (let or const, const preferably) and the name of the variable will be used as the name of the function. The below code shows the syntax difference between the normal functions in Javascript and Arrow functions in Javascript:

//normal function
function getSquare(num){
  return num * num;
}

//arrow function
const getSquareArrow = (num) => {
  return num * num;
}


var template = <div>
<p>{ getSquare(5) }</p>
<p>{ getSquareArrow(3) }</p>
</div>;

The is also another concise short hand syntax of Arrow function if we are going to return only the value of a single expression and below is an example for the same:

//concise arrow function syntax
const getSquareArrow = (num) => num * num;

Here in this code, the result of the expression is implicitly returned.

Related Posts