📜 ⬆️ ⬇️

Introduction to arrow functions in javascript ES6

“Thick” pointer functions (=>), also known as arrow functions, are completely new functionality in ECMAScript 2015 (previously known as ES6). If you believe the rumors, in ECMAScript 2015 => the syntax was used instead of -> syntax influenced by CoffeeScript . Also, the similarity of the transfer of this context played a significant role.

The switch functions have two main tasks: to provide a more concise syntax; to ensure the transfer of lexical this with the parent scope. Let's take a closer look at each of them!

New syntax of functions

The classic syntax of functions in JavaScript is distinguished by its rigidity, be it a function with one variable or a page with many functions. With each function declaration, you need to write function () {}. The need for a more concise syntax of functions was one of the reasons why CoffeeScript became very popular in its time. This need is especially evident in the case of small callback functions. Let's just take a look at the Promise chain:
function getVerifiedToken(selector) { return getUsers(selector) .then(function (users) { return users[0]; }) .then(verifyUser) .then(function (user, verifiedToken) { return verifiedToken; }) .catch(function (err) { log(err.stack); }); } 

At the top, you see more or less digestible code written using the classic JavaScript function syntax. And here is the same code rewritten using the arrow syntax:
 function getVerifiedToken(selector) { return getUsers(selector) .then(users => users[0]) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack)); } 

Here it is necessary to pay attention to several important points:

Let's pay attention to the last point. Implicit return occurs only in the case of single-line arrow functions. When the switch function is defined with {}, even if it is a separate statement, implicit return does not occur.
 const getVerifiedToken = selector => { return getUsers() .then(users => users[0]) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack)); } 

This is where the fun begins. Since our function has only one operator, we can remove {}, and the code will be very similar to the CoffeeScript syntax:
 const getVerifiedToken = selector => getUsers() .then(users => users[0]) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack)); 

Still, the code above is written using the ES2015 syntax. (I was also surprised that it compiled perfectly .) When we talk about switch functions with one operator, this does not mean that the operator cannot occupy more than one line, for ease of use.

There is, however, one significant disadvantage: removing {} from the switch functions, how can we return an empty object? For example, the same {}?
 const emptyObject = () => {}; emptyObject(); // ? 

And this is how the whole code looks like together:
 function () { return 1; } () => { return 1; } () => 1 function (a) { return a * 2; } (a) => { return a * 2; } (a) => a * 2 a => a * 2 function (a, b) { return a * b; } (a, b) => { return a * b; } (a, b) => a * b function () { return arguments[0]; } (...args) => args[0] () => {} // undefined () => ({}) // {} 

Lexical this

The story of how this tried to push through in JavaScript has already become covered in dust. Each function in JavaScript sets its own context for this. This context, on the one hand, is very easy to get around, and, on the other hand, it is extremely annoying. In the example below, you see the code for the clock, which updates the data every second, referring to jQuery:
 $('.current-time').each(function () { setInterval(function () { $(this).text(Date.now()); }, 1000); }); 

When we try to refer to this DOM element, given through each in the setInterval callback, we unfortunately get a completely different this, the one that belongs to the callback. You can bypass this moment by setting the variable that or self:
 $('.current-time').each(function () { var self = this; setInterval(function () { $(self).text(Date.now()); }, 1000); }); 

“Thick” pointer functions can help solve this problem, since they do not have this:
 $('.current-time').each(function () { setInterval(() => $(this).text(Date.now()), 1000); }); 

What about the arguments?

One of the drawbacks of the switch functions is that they do not have their own arguments variable, like ordinary functions:
 function log(msg) { const print = () => console.log(arguments[0]); print(`LOG: ${msg}`); } log('hello'); // hello 

Again, the switch functions do not have this and no arguments. However, taking this into account, you can still get the arguments passed to the arrow functions using the rest parameters (also known as spread operators):
 function log(msg) { const print = (...args) => console.log(args[0]); print(`LOG: ${msg}`); } log('hello'); // LOG: hello 

What about generators?

“Thick” switch functions cannot be used as generators. There are no exceptions and workarounds. Point.
')
Conclusion

“Thick” arrow functions are one of the reasons why I love JavaScript so much. It is very tempting to just start using => instead of function. I have seen entire libraries where only option => is used. I do not think, however, that it is reasonable. In the end, => there are many features and hidden functions. I recommend using arrow functions only where you need new functionality:

ES6 today

So is it possible to take advantage of ES6 today? The use of transpilers has become the norm in the last few years. Neither simple developers nor large companies feel free to use them. Babel is a transpiler from ES6 to ES5 that supports all the innovations of ES6.

If you use Browserify , you can add Babel in just a couple of minutes . Of course, there is support for almost any build with Node.js. For example: Gulp, Grunt and many others.

What about browsers?

Most browsers are gradually adding new features , but no one has yet got full support. What now to wait? It depends. It makes sense to start using language features that will become universal in a year or two. This will allow you to comfortably move to a new stage. However, if you need 100% control over the source code, then for now it's better to wait and use ES5.

Translation prepared by: greebn9k (Sergey Gribnyak), silmarilion (Andrey Khakharev)

Source: https://habr.com/ru/post/268795/


All Articles