ES6 Lesson #11 - Arrow Functions

Nevertheless, jаvascript remains a functional language, in this tutorial we will look innovations in es6 functions. Namely arrow functions.

Now it is possible to write single-line functions that return a result without operator return.

See an example of old and new syntax:

// old
var rcn_old = function(prop1, prop2) {
  var st = prop1 + prop2;
  return st
}

// new
let rcn_new = (prop1, prop2) => prop1 + prop2;

// Result
console.log(rcn_old(5, 5))
console.log(rcn_new(5, 5))

As we can see, this code is more short. But if you need several lines in a function, you still have to use the return statement.

let rcn_new = (prop1, prop2) => {
   let st = prop1 + prop2;
   return st;
}

console.log(rcn_new(5, 5))

As you can see, the arrow function is written without a name, it is written in a variable. If you need to register an anonymous function, for example for a loop, then just write ()=>

For example:

let array = [1,2,3,4,5]

array.forEach((element, index) => {
    console.log(element)
    console.log(index)
});

array.forEach(element => {
    console.log(element)
});

If a function accepts only one parameter, then you don’t even need to bracket it

If you need to write a function that is called immediately, then this can also be done.

// old syntax
(function() {
  console.log(1)
})();

var vad = (function() {
  console.log(1)
})();


//new
(() => console.log(1))();

(() => {
 console.log(1)
 console.log(2)
})();

let vas = (() => console.log(2))();

At first glance, everything is simple, but arrow functions have a difference that distinguishes them from ordinary ones.

If you apply the this property inside the object, then the default function will return you an object, but arrowfunction return window.

//default func 
var person = {
   name: "Valera",
   hello: function() {
      console.log(this)
   }
}

person.hello(); // return object

// arrow func
let person2 = {
   name: "Yosip",
   hello: () => {
      console.log(this)
   }
}

person2.hello() // return window 

And this is done for a reason.

If in jаvascript you try to 'setTimeout ()' inside a function, then this property will belong to setTimeout(). The arrow function inherits the parent, so in the arrow function you get the parent.

var person = {
   name: "Valera",
   hello: function() {
      setTimeout(function() {
         console.log(this)
      }, 100)
   }
}

person.hello(); // return window


var person2 = {
   name: "Valera",
   hello: function() {
      setTimeout(() => {
         console.log(this)
      }, 100)
   }
}

person2.hello(); // return object


var person3 = {
   name: "Valera",
   hello: () => {
      setTimeout(() => {
         console.log(this)
      }, 100)
   }
}

person3.hello(); // return window

Therefore, given this situation, arrow functions are not a replacement for the main ones, but only for their addition. 🙄