What do you mean by ES6 in angularJS

Karthik G

ES6 in angularJS
ES6 or ECMAScript 6 which is the latest version of ES5 with many added features. Using most of the ECMAScript 6 features in your project is pretty easy. You plug in a compiler like Babel into your build chain and it will just compile your ECMAScript 6 code to ECMAScript 5, which runs just fine in any modern browser.

Requirement to write ES6 code

Setting up Babel in your program:
The easiest way to enable ES6 in your project with gulp is by taking advantage of the gulp-babel plugin. You can install it via npm.
The command to install → npm install –save-dev babel-preset-2015 gulp-babel
Once this has been installed, now you have to include this in your gulpfile.js as,

var babel = require(‘gulp-babel’);

gulp.task(‘js’, function() {
return gulp.src(‘app/**/*.js’) // select all js files in the app folder
.pipe(print()) // print each file in the stream
.pipe(babel({ presets: [‘es2015’] })) // transpile ES2015 to ES5 using ES2015 preset
.pipe(gulp.dest(‘build’)); // copy the results to the build folder
});

Now to run the program you have to run by running “gulp js”, which should do the job. To check or to convert manually, check this out.

ES6 coding

Before jumping into coding, we need to understand few features to be used.
– Let and const
– Arrow functions
– Template literals
– Classes
– Symbols
– Iterators
– Generators
– Promises
– Maps
– Sets

Using let and const:
For the longest time, the only way to declare a variable was with the var keyword. Now that we have two new types of declaring, we will go through it now.

For example to declare a variable called “foo”, we go as,

function(){
var foo = “whatever”; // let foo = “whatever”;
}

Now, as we know, the variables we declare using var has a function scope to it. That means the variable foo is accessible only inside the function it has been declared. Now instead of var we can use “let” which has the similar properties as “var”, except that it makes the declared variable a block scope instead of function scope.

Now talking about const, as the name suggests, the variable declared with const cannot be re-assigned.

For example,

const foo = “foo”;

foo = “foo1”;

Now foo will still have foo as its data and not foo1.

But when you do this,

const foo = {
one : {
two = “goodbye”;
}
}
foo.one.two = “notgoodbye”;

In this example, two will be modified to notgoodbye.

Using arrow functions:
This is actually a small change but used humorously while coding ES6 in angularJS. This is actually a replacement to the function keyword in ES5, with a slight change which you will see below.

In ES5:

var things = [0,1,2,3];
things.map(function(thing){
console.log(thing);
});

Here you will see the output, 0 1 2 3.

In ES6:

var things = [0,1,2,3];
things.map(thing => console.log(thing));

Still we get the same expected output. Whats happening here is that, for each thing in an array, it is being consoled.

Template literals:
These are also called as template strings. We will understand the difference by this example.

console.log(`hello`);

This acts same as console.log(“hello”);

This is not the big and important difference in this. Now if we want to write a hello world in different line, we have to do a lot of work in double quotes.

console.log(“hello\n”+
+“world”);

Using template literals, we have this feature as,

console.log(`hello
world`);

This works exactly the same as before, except we do not have to use many ugly characters in this case. Now let’s see these using variable.

var foo = ‘bar’;
var baz = ‘bar’;

console.log(“The first thing is “ + foo + “ and the second thing is “ + baz);

Now you can get rid of this + by using this template literals.

var foo = ‘bar’;
var baz = ‘bar’;

console.log(`The first thing is ${foo} and the second thing is ${baz}`);

Now this is much cleaner and simple code with all the + and spaces and double quotes eliminated, which gives exact the same output as before.

Classes:
This is pretty big topic. So lets go through this thoroughly. Now lets go through the basic syntax of this.

class person{
constructor (age, height){
this.age = age;
this.height = height;
console.log(this.age, this.height);
}
}

Now this looks familiar to ruby, rails. But this javascript is not the object oriented language. It just inherited the property of classes, to get a clean and better understanding of the code. Now we can do ahead and create objects, to assign the age and height too.
var person = new person(28 , “6 feet”);

This will get us the output as age 28 and height as 6 feet. Now you can also have methods inside a class, for example, get and set methods.

class foo{
constructor (first, second){
this.first = first;
this.second = second;
}
get total(){
return this.first + this.second;
}
}

var foo = new foo(5 , 5);
console.log(foo.total);

Now you can also extend classes, like:

class cat{
constructor (name){
this.namer = name;
}
speak(){
console.log(this.name + ‘ makes a noise.’);
}
}
class lion extends cat{
speak(name){
super.speak();
console.log(this.name + ‘ roars.’);
}
}

var meow = new lion(‘meow’);
meow.speak();

Now here super.speak() will call the cat class and the lions console will be printed later.
Symbols:
Now for the longest time, javascript has been using six types.
– Undefined
– Null
– Boolean
– Number
– String
– object

Now this symbols comes under the seventh type.

var sym = Symbol(“foo”);

console.log(typeof sym);

Now the output will be “symbol”. So this isn’t build upon any string or type. This is the unique type.

console.log(Symbol(“foo”) === Symbol(“foo”));

console.log(Number(3) === Number(3));

Now this will return false and true. This is because, when you compare a number or a string or object, you return the same data. But with a symbol, it’s merely a description of a symbol.
As far as I understand, this symbol is used to create a unique id for each created thing.
If you create “foo” three times, three foo’s will be different. But I have very little knowledge of why one has to use this symbol.

Generators and Iterators:
Before beginning, you have to understand that generators are special type of function that can pause or resume state. Now lets begin with the basic kind of generators.
function* neverending(){
let index = 0;
while(true){
yield index++;
}
}
let gen = neverending();
In the above example, the new things are * and the yield, which are related to generators. One point is worth mentioning, the relationship between the generators and the iterators is such that ,
function* is itself a generator function which yields something, and it returns a generator. Now if you just console “gen.next()”, you will be getting index as 0 along with the object “done” which can be true or false. This indicates if the generator is iterable or not.

function* neverending(){
let index = 0;
while(index < 2){
yield index++;
}
}
let gen = neverending();
while(gen.next().done === false){
console.log(gen.next());
}

This will console only till done is false, and it becomes true for the third iteration. One important thing to remember here is that, it saves states. You can also throw errors like,

console.log(gen.throw(new Error(‘oops!’));

Now, you can call generators from inside the generators too. As we declare a function with a * to be a generator, you can declare a yield with a * to be a yield generator.

function anothergenerator(i){
yield i+1;
yield i+2;
yield i+3;
}
function generator(i){
yield i;
yield* anothergenerator(i);
yield i+10;
}

var gen = generators(10);

console.log(gen.next().value); //10
console.log(gen.next().value); //11
console.log(gen.next().value); //12
console.log(gen.next().value); //13
console.log(gen.next().value); //20

So the important thing to remember here is the * symbol and the yield symbol. Here .next is the iterator function which is used to get the value of the next item. Therefore we can say that the iterator next() gives us a output as value and an object called done. You have to use the iterators no matter if it an array, or an object or map.

Promises:
Promises are created to overcome the callback hell in asynchronous programming. Angularjs is having the $q library to implement it. In angular ES5 we will use two callback functions like success and error, But in promises, we will handle that in single callback called then. This will accept two parameters first one is for success resolve function the second one is error handling function. Finally, this function will return a promise for further steps. So the future operations, which are dependent on previous functions will receive some response to continuing the operation. It can be an error response too.
By using promises, we can resolve all exceptions in callback functions.
Eg: In .js file:
//this function will return a promise
someCallbackFunction(){
return $q((resolve,reject)=>{
asynchronousFunction((success)=>{
deferred.resolve(success);
},(error)=>{
deferred.reject(error);
});
});
}
//the following code will use that promise for further actions
someCallbackFunction().then((data)=>{
//success block
},(reason)=>{
//error block
})

 

about the author

Karthik G

Karthik, currently working at Techjini, has experience in developing front-end web applications. He has worked in platforms like AngularJS. Keen to learn new technologies.