📜 ⬆️ ⬇️

Ecmascript 6 - what you can use now



Note: The article is intended mainly for non-Javascript programmers - sometimes I will go into explaining quite basic things, but I hope it will be useful for those who just did not have time to familiarize themselves with most of the innovations of ES6.

As you know, the standard Ecmascript 6 are going to be published in June 2015 . But since so much has already been implemented in modern browsers , why not start using it right now?
Since jsFiddle and ES6 analogues do not support, I will use es6fiddle for examples. Unfortunately, not everything in it can be shown because of bugs. In the absence of references to es6fiddle, I recommend copying the code snippets to the modern browser console and executing them - for clarity. I recommend the extremely stable Firefox (version 33 at the time of this writing) - everything works out of the box.
')


Since there are a lot of changes, I will describe the subjective most important ones.

let and scope - variables with block scope


One of the most annoying / incomprehensible things for beginning JS programmers is the scope of variables in JS. Example:
for(var i=0; i<10; i++){ } console.log(i); 


In most languages, such a code will throw an error that i is not defined, but in JS the number “10” will be displayed in the console. The reason is that JS uses hoisting - that is, the declarations of all used variables are transferred to the beginning of the function (and, accordingly, i is available outside the for block). That is why it is advised to declare all variables at the beginning of a function — they will still be transferred there when the code is executed.
In ES6, you can write:
 for(let j=0; j<10; j++){ } console.log(j); 


In this code, the scope of j is bounded by a for block. It no longer makes sense to declare variables at the beginning of a function!

There is nothing special to say about const - this is a constant declaration, when reassigning a value, it throws a TypeError (in strict mode).

Example:
 function setConst(){ "use strict"; const xx = 10; xx = 11; console.log(xx); } setConst(); 


There are no links to examples, since at the moment the block scope in es6fiddle is not supported. We are waiting for fixes.

Arrow functions


If you used lambdas in C #, you immediately recognize the syntax (this is not an accident - it was taken from there ).
As written before:
 function SomeClass() { var self = this; //       self.iter = 0; setInterval(function() { self.iter++; console.log('current iteration: ' + self.iter); }, 1000); } var sc = new SomeClass(); 


In ES6 it can be much simpler:
 function SomeClass() { this.iter = 0; setInterval(() => { this.iter++; console.log('current iteration: ' + this.iter); }, 1000); } var sc = new SomeClass(); 

es6fiddle

As you can see, the arrow function does not create its own context, so this will point to the context of the function in which the code is called.

Example with parameters:
 let numList = [1,2,3]; let doubleNumList = numList.map(n => n*2); console.log(doubleNumList); 

es6fiddle

Compare how much more bulky the old method is:
 let numList = [1,2,3]; let doubleNumList = numList.map(function(n){ return n*2; }); console.log(doubleNumList); 


Classes


The old way to emulate classes in JS looks something like this:
 function Vehicle(topSpeed){ this.topSpeed = topSpeed; this.printTopSpeed = function(){ console.log('Top speed:'+this.topSpeed+' km/h'); } } var myVehicle = new Vehicle(50); myVehicle.printTopSpeed(); 

jsFiddle

“Traditional” inheritance as in Java / C # can also be emulated through the prototype model (I will not give the code, so as not to inflate the article).
In ES6, "real" classes appear:
 class Vehicle { constructor(topSpeed){ this.topSpeed = topSpeed; } printTopSpeed(){ console.log('Top speed:'+this.topSpeed+' km/h'); } } class Bicycle extends Vehicle { constructor(topSpeed, wheelSize, bicycleType, producedBy){ super(topSpeed); this.wheelSize = wheelSize; this.bicycleType = bicycleType; this.producedBy = producedBy; } static wheelCount(){ return 2; } get bikeInfo(){ return this.producedBy + ' ' + this.bicycleType + ' bike'; } printBicycleType(){ console.log('Type:'+this.bicycleType+' bike'); } } var myBike = new Bicycle(40,622,'road','Trek'); myBike.printTopSpeed(); myBike.printBicycleType(); console.log('Bicycles have '+Bicycle.wheelCount()+' wheels'); console.log(myBike.bikeInfo); 

es6fiddle

I think that the code above does not need comments. As you can see, in classes you can define getters and static methods (but not fields), the syntax is intuitive. It is worth noting that the class body is always interpreted in strict mode. And, of course, no one makes frantic adherents of the prototype inheritance to change their habits - classes are generally syntactic sugar on top of the old model.

Destructuring assignment


Finally, a small but interesting feature that facilitates the assignment of values. Example:
 function getFirstPrimeNumbers(){ return [2,3,5]; } var [firstPrime, secondPrime, thirdPrime] = getFirstPrimeNumbers(); console.log(thirdPrime); //5 //  (value swap) var [x,y] = [1,2]; console.log('x:'+x, 'y:'+y); //x:1 y:2 [x,y] = [y,x]; console.log('x:'+x, 'y:'+y); //x:2 y:1 

es6fiddle

Now you can exchange values ​​without a temporary variable, which reduces the code.

A slightly more complicated example:
 var myBook = { title: "Surely You're Joking, Mr. Feynman!", author:{ firstName: 'Richard', lastName: 'Feynman', yearBorn: 1918 } }; function getTitleAndAuthorsLastName({ title, author: { lastName } }){ return 'title: '+ title + ' last name:'+lastName; } console.log(getTitleAndAuthorsLastName(myBook)); 

es6fiddle

How to use?


I foresee a disturbance - as can be seen from the same table , in some places ES6 does not work right away. Chrome, for example, does not support most things from the list, unless the Enable Experimental JavaScript flag is enabled . The solution is to use Traceur , the compiler from ES 6 to ES 5.
That it is used in es6fiddle, by the way. On the page in the githaba there are instructions for use . In short for the browser:

1. Connect 2 JS files:
  <script src="https://google.imtqy.com/traceur-compiler/bin/traceur.js"></script> <script src="https://google.imtqy.com/traceur-compiler/src/bootstrap.js"></script> 

2. Add to support ES6 experimental features:
  <script> traceur.options.experimental = true; </script> 

3. We write code in script tags with module type:
 <script type="module"> let a = 10; </script> 


Conclusion


I hope that this article was able to show that Javascript at the moment has developed into a rather serious programming language (albeit with some strange behavior). This does not mean that you should throw your favorite Java / C # / C ++ in the trash, it means that it became even easier to master javascript, due to convenient syntax and more stable behavior.

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


All Articles