In my first post of this series, I covered some Introduction to ES6 and also wrote about how to setup your local machine to transpile ES6 with babel. In this post, I’ll explore ES6 classes and Arrow Functions.
Arrow Functions in ES6
So I promised that I’ll do all this while solving some very trivial programming tasks. So here is my task.
#Task 1: Write a Simle Currency Calculator that takes three Arguments, a Number for Conversion Rate, and two ISO 4217 Currency Strings and returns a function that converts any amount from one currency to another.
Solution: I did this thing via new Arrow functions in ES6, and actual Currency Converter code was just one line.
Cool, Right! ES6 Arrow function make it really easy to write short functions. And If you have used Coffeescript, then you already might be seeeing some similarity.
I’ll use the above Currency Converter Example to make and use an ES6 class. Also I’ll extend that class to show how inheritance works in ES6.
Here I have written a dead simple ES6 class for Currency. It contains just one constructor and one function toStringAmount.
ES6 classes are much easier to write, extend and instantiate. They work like classes from many other programming languages that you may be familiar with. So How are we doing this now in ES5? Below is the ES5 way.
Extending ES6 Classes
Extending classes is quite important topic, Since Its in the core of Object Oriented Programming. Its good old inheritance. Until now, you achieved this kind of thing via Prototypes and stuff, But with ES6 you can get inheritance with extends keyword. So lets see how this thing works.
#Task2: I’ll be writing a vehicle class, from which Car Class will extend, and that will indeed extend to Jaguar Class.
ES6 Further Reading
Mozilla Hacks “Arrow Functions in Deep“.
And What people are saying[tweet https://twitter.com/stepan_kouba/status/610152458753589248] [tweet https://twitter.com/BrendanEich/status/609525681609781248]
Are they? But I didn’t do a lot of Java myself, so I can say.[tweet https://twitter.com/BigstickCarpet/status/610155146866135040] [tweet https://twitter.com/babeljs/status/609798734650589184]
I might buy this book soon. I am big ES6 fan anyway.
So In this post I talked about Arrow Functions and ES6 classes from top level. I didn’t go very deep, because there is so much to talk about ES6, that I would have to write day and night for weeks. Just Kidding.
In Next post, I’ll talk about ES6 modules and Iterators.