ES6 features- Arrow Functions Examples | ES6 tutorials

In this blog post, We are going to learn the basics of Arrow functions in javascript with examples.

Why Arrow Function

Let us create a normal function declaration in javascript. The function has a name, parameters, and body.

function incrementByOne(value) {
  return value + 2;
}
incrementByOne(2);

The same above code is rewritten with new syntax -the same function with shorter syntax. This is an arrow function and omitted function name, curly braces, and return statement. Implicit return is not required. Syntax contains fat arrow =>

var incrementByOne = (value) => value + 2;
incrementByOne(2);

Syntax

(parameters) => {
  statements / expression;
};

here are parameters that can be optional or many statements which have no return type curly braces are not required Expression is code which requires curly braces Ways to declare Arrow functions. We will see different cases of declaring arrow functions. no parameters syntax

() => {
  statements / expression;
};

One parameter syntax

value => { ... }

Multiple parameters Syntax

(x, y) => { ... }

Arrow functions example

var strs = ["one", "two", "three", "four"];
console.log(strs.map((strs) => strs.length));

Arrow functions errors/undefined examples

This will not work as expected in the below cases.

new and constructor usage

with arrow functions throws Uncaught TypeError: MyObj is not a constructor

function MyObj1() {}
var myobj1 = new MyObj1();
console.log(myobj1); // outputs object
var MyObj = () => {};
var myobj = new MyObj();

console.log(myobj); // TypeError: MyObj is not a constructor

Prototype method usage

Array functions with prototype method return undefined.

var MyObj = () => {};
console.log(MyObj.prototype); // outputs undefined
function MyObj1() {}
console.log(MyObj1.prototype); // outputs object

yield keyword also will not work in arrow functions