📜 ⬆️ ⬇️

Javascript es6: write less - do more

The ES6 standard brought new syntactic constructs and remarkable features to the world of JavaScript, which, among other things, improve the readability of program texts, make them more concise and expressive. All this allows the developer to solve the same tasks as before, writing less code. “We write less - we do more” - this is the idea that inspired the author of the material, which we are publishing today, to explore the possibilities of ES6. In particular, here he compares ES5 and ES6 and considers options for the practical use of new designs.

image

Keywords const and let


In ES6, a new keyword const , which is used to declare so-called immutable variables, or simply constants. Such variables are different from those declared with the var keyword, since they cannot be changed after initialization. It should be noted that we are talking here only about the value of the constant itself, and if, for example, it is an object, the internal structure of such an object can be changed.

Using the const keyword is very useful for working with selectors. For example, if we have a button that triggers an event to work with in the code, or some other HTML element, to access them from JS it’s best to use const , rather than var , if the selector is not changed planned.
')

In the above example, the value written to the constant cannot be changed. When we try to write a new value to it, we will encounter an error message.

Speaking about the const keyword, it should be noted that the immutable variables declared with its help have a block scope. The same can be said about ordinary variables declared using the new let keyword. Such variables can be reassigned, as declared with the var keyword, but var characterized by raising variables, while what is declared with let and const does not exist before the declaration. That is, for example, you can access a variable declared with let only after it is declared.


Arrow functions


Arrow functions - just a great opportunity. They improve readability and have a beneficial effect on the structure of the code, and they simply make the programs look more modern. Here's how to use the features in ES5.


But the modern version.


Note that due to the new syntax, you can refuse to use curly braces and the keyword return . The new code is more convenient to read, it looks cleaner.

In addition, the pointer functions can be used with the built-in map , filter and reduce functions.


The code of the map function, to which the switch function is passed, looks cleaner and more readable than the similar code created by ES5 tools. The same is true for the filter and reduce functions. The code is shorter, it is more convenient to work with it.

Pattern Literals


Pattern literals, or pattern strings - a very interesting opportunity. Now you do not need to use the + operator to concatenate strings, or in cases when strings are used to assemble strings. Here is how it looked before.


That's what we have now.


In a new way it turns out much easier. Before us is a very significant difference between the old syntax and ES6. New features of ES6 make working with strings more organized and contribute to improving the structure of the relevant code fragments.

Default Function Parameters


The author of the material says that when he writes in PHP, he usually uses the default function parameters. This allows you to set some parameters of the functions in advance. As a result, if you do not specify a parameter when calling the function, it will not be equal to undefined , its default value will be used instead.

Consider an example in which default parameters are not used.


As you can see, undefined appears in the output of the function, since we forgot to pass the function the parameter age . However, when using the default parameters in the output generated by the function, undefined will not appear.


As you can see, the function returns a string without undefined values, even if the second parameter is not passed when calling it. The use of default parameters allows for situations of nonstandard function calls.

Destructuring arrays and objects


Destructuring simplifies the assignment of individual values ​​stored in arrays or objects to new variables. Here's how this could have been done before.


Here's how the same thing is done with ES6 tools.


Using ES5, we had to assign each separately taken value to each variable. Due to the capabilities of ES6, in order to extract individual values ​​of the object, it is enough to place the variable names in curly brackets.

Pay attention to the fact that if in a similar construction with curly brackets there are variable names that do not have correspondences among the object property names, they will take the value undefined . For example, if the property name of the object is name , and we attempt to assign the value of this property to the variable username , it fails, this variable will get the value undefined . Variables should always be named the same as object properties. If you want to use a variable with a different name, you need to use a construction in which first comes the variable name corresponding to the name of the object property, then the colon, and finally the new variable name. It looks like this.


In the case of arrays, a similar syntax is used. Only curly brackets should be replaced by square brackets.


Import and export instructions


Using import and export statements in JS applications expands their capabilities. They allow the programmer to create standalone components suitable for reuse.

If you are familiar with any MVC framework for JavaScript, you already know that they almost always use import and export instructions to work with components. How does all this work? In fact - very simple. The export allows you to export a module that can be used in other JavaScript components. The import used to import such modules.

Suppose we have a pair of files - detailComponent.js and homeComponent.js .

In the detailComponent.js file detailComponent.js we want to export the detail function. Here's how to do it.


Now, if we need to use this function in homeComponent.js , the import statement will help us with this.


If you need to import multiple modules, you can list them in curly braces.


Promises


Promises are one of the new features of ES6. This is an approach to writing asynchronous code. It can be used when, for example, you need to load data from a certain API, or when we have a function that needs some time to execute. Promises simplify the solution of such problems. Here's how to work with them.


It shows what will get to the console when trying to log promis.

If you need to perform some function after, for example, data has been received, which takes time to load, we can use promis. Promis takes two parameters, resolve and reject . The first is used in the successful resolution of the promise, the second - to handle the expected errors. In the following example, notice that the fetch function itself returns a promise.

 const url='https://jsonplaceholder.typicode.com/posts'; const getData=(url)=>{   return fetch(url); } getData(url).   then(data=> data.json()).   then(result=> console.log(result)); 

In this case, calling console.log results in an output to the console of the array.

Syntax of the remaining parameters and the extension operator


The syntax of the remaining parameters is used to represent an unlimited set of arguments as an array. Here are some examples of its use.


The extension operator is similar to using the syntax of the remaining parameters, but it allows, as shown in the following example, to work with arrays, extracting their values, which otherwise would have to be extracted using a for loop or some other method.


Classes


Classes are one of the basic concepts of object-oriented programming. They allow you to improve the structure of the code and make it safer.


To declare a class, you can use the class keyword followed by the name of the class with a pair of curly braces.


Now, based on the class, you can create a new object using the new keyword.

 class myClass{   constructor(name,age){       this.name=name;       this.age=age;   } } const Home= new myClass("said",20); console.log(Home.name)//  said 

Classes support the inheritance mechanism. To use it, the extends keyword is used, followed by the name of the class from which they want to inherit.


Here you can read details about classes in JavaScript.

Results


We hope this material has helped you discover among the opportunities of ES6 something new, useful in your practical work. By the way, not all the innovations of ES6 are described here. You can get acquainted with their much more extensive list here . In addition, if you are interested in the topic of new features of JavaScript, here , here and here - some of our publications on this topic.

Dear readers! Can you give examples from practice illustrating the idea that using the new features of ES6 allows you to solve the same tasks as before, with the help of a smaller amount of code that, moreover, turns out to be simpler, clearer and more readable?

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


All Articles