Loading Now
×

All about  es6 

All about  es6 

In all environments, ES6, the new version of JavaScript, allows us to write code more simply and elegantly. Compared to ES5, ES6 often requires less code and solves many problems with fewer lines of code. It looks nice, involves fewer lines of code, and is smarter in every way. So, should we still use ES5 or switch to ES6? From one perspective, due to the new syntax and many other advantages of ES6, it might be wise to use ES6. Additionally, as developers, we don’t like to stay outdated. Therefore, if we want to stay updated, we should start using ES6 now.

But there’s a catch! Since ES6 is relatively new, you need to consider whether this code will be supported on all devices before using it in your application. It’s not possible to individually check whether the devices using your application will support it or not. However, if you are sure that your application will run on specific devices or environments where ES6 is supported, you can safely use it directly. But in most cases, we don’t have a clear idea about the environment. In such cases, it’s better to write code in a version that is safer, like ES5, which is fully supported in almost all major environments.

But how do we know which code is supported where? For that, you can check this website [https://link.zonayed.me/JS-Compat]. Although most of the features of ES6 are now supported in major environments (browsers, Node.js), there are still some environments where it is not fully supported. This means using ES6 is not yet completely safe, and it is often not used in production. But does that mean we shouldn’t use ES6? Of course, we should! Most frameworks nowadays use ES6. You will also see other developers or during work that ES6 syntax is used to write code. Since ES6 is relatively clean and easy to write, it is quite popular in the developer community. However, even if ES6 syntax is used during development, usually ES5 code is delivered with the actual application in production. Since ES6 is not yet fully supported, the final product is delivered using ES5.

But developers prefer to use ES6 syntax during development because it is clean and easy. Later, many tools can be used to convert it to ES5 for the actual production version. We will also see in this chapter how to write ES6 code and easily convert it to ES5. If you go to this website [https://babeljs.io/en/repl], you will find a live REPL. If you input ES6 code on the left side, you will get ES5 code on the right side. From here, you can easily convert your code. Let’s look at some demos.

“`

Look at this, it gets converted on the left side, and the code looks like this:

1  2 ‘use strict’;

3 var name ‘Zonayed Ahmed’; = 4 var anoName = ‘Zawad Ahmed’;

Then we can see it with the Template Literal syntax:

const name = ‘Zonayed Ahmed’, age = 21, work = ‘Student’;

console.log(`My name is ${name} and I’m ${age} years old! Currently I’m a ${work}`);

It also gets converted to ES5 syntax:

1 ‘use strict’;

2 3 var name = ‘Zonayed Ahmed’,

4 age = 21,

5 work = ‘Student’;

6 console.log(‘My name is ‘ + name + ‘ and I\’m ‘ + age + ‘ years old! Currently I\’m a ‘ + work);

The same applies to arrow functions:

const aArrowFunc = () => { }

const sum = 10 + 20;

console.log(sum);

gets converted to:

1 “use strict”;

2 var aArrowFunc = function aArrowFunc() {

3 var sum = 10 + 20;

4 console.log(sum);

5 };

“`

Sure! Here’s the translation of your text into English:

We saw the new syntax for constructor functions when writing code using the `class` keyword. Here’s an example:

“`javascript

class Child6 {

    constructor(name, dob) {

        this.name = name;

        this.dob = dob;

    }

    currentAge() {

        console.log(`${this.name} is ${2018 – this.dob} years old!`);

    }

}

“`

Notice that in ES5, a large amount of code is generated:

“`javascript

“use strict”;

var _createClass = function () {

    function defineProperties(target, props) {

        for (var i = 0; i < props.length; i++) {

            var descriptor = props[i];

            descriptor.enumerable = descriptor.enumerable || false;

            descriptor.configurable = true;

            if (“value” in descriptor) descriptor.writable = true;

            Object.defineProperty(target, descriptor.key, descriptor);

        }

    }

    return function (Constructor, protoProps, staticProps) {

        if (protoProps) defineProperties(Constructor.prototype, protoProps);

        if (staticProps) defineProperties(Constructor, staticProps);

        return Constructor;

    };

}();

function _classCallCheck(instance, Constructor) {

    if (!(instance instanceof Constructor)) {

        throw new TypeError(“Cannot call a class as a function”);

    }

}

var Child6 = function () {

    function Child6(name, dob) {

        _classCallCheck(this, Child6);

        this.name = name;

        this.dob = dob;

    }

    _createClass(Child6, [{

        key: “currentAge”,

        value: function currentAge() {

            console.log(this.name + ” is ” + (2018 – this.dob) + ” years old!”);

        }

    }]);

    return Child6;

}();

“`

This example highlights the difference between the concise ES6 class syntax and the more verbose ES5 code generated by a transpiler like Babel.

“”   So far, you can convert almost all the new ES6 syntax here. But there are some that are a bit difficult. For example, we introduced a new data structure called Map in ES6. You cannot easily convert Map: 

“`javascript

const zawad = new Map();

zawad.set(‘fullName’, ‘Zawad Ahmed’);

zawad.get(‘fullName’);

“`

If you look on the right side, you will see the same thing, it has not been converted:

“`javascript

1 ‘use strict’;

2

3 var zawad = new Map();

4 zawad.set(‘fullName’, ‘Zawad Ahmed’);

zawad.get(‘full Name’);

“`

Now, to convert this as well, we need to use a Babel plugin. If you look at the left side of the Babel REPL, you will see there are some options. Among them, you will find an option called Plugins:

> PLUGINS

Open this and click on Add Plugins to add a plugin named babel-plugin-transform-runtime:

PLUGINS

babel-plugin-transform-runtime

“””

Here’s the translation of the given text to English:

If you add it, you’ll see that the syntax of this new map has also been converted:

“`javascript

‘use strict’;

var map = require(‘babel-runtime/core-js/map’);

var _map2 = _interopRequireDefault(_map);

function _interopRequireDefault(obj) {

  return obj && obj._esModule ? obj : { default: obj };

}

var zawad = new _map2.default();

zawad.set(‘fullName’, ‘Zawad Ahmed’);

zawad.get(‘fullName’);

“`

Here, you can manually convert ES6 or higher version code to ES5 code. For a small amount of code, this is okay, but what if there is more code or it’s a project? Yes, in that case, this method is indeed time-consuming and also annoying. But there is no reason to worry; you might use a framework for your work. Most modern frameworks or libraries are set up in such a way that you write the code in ES6, and they automatically convert that code to ES5 or as needed. You don’t have to think about it at all. You just keep writing code using ES6 syntax. So, it doesn’t really become a big problem. But still, we’ll see how we can set up an environment like this ourselves, which will take our ES6 code to ES5.

If you are not familiar with the tasks I will do here, you might not understand some of them. But I suggest you just follow along with me. And you’ll get some idea of how powerful JavaScript is and that it can work outside the browser as well.

For this, we need to have Node.js installed first. If you haven’t installed it yet, download and install the LTS version from [https://nodejs.org/]. Then, open your preferred command line or the command line that comes with your system and check whether Node.js is properly set up by using the following commands. I use cmder [http://cmder.net/] as my command line:

“`bash

node -v

“`

If everything is okay, you will get an output like this:

“`

C:\Users\Zonayed Ahmed A

node -v

v8.11.3

“`

Here’s the translation of the additional text to English:

Your version number might be higher here. Next, run another command:

“`bash

npm -v

“`

You will get an output like this:

“`

C:\Users\Zonayed Ahmed λ npm -v

5.6.0

“`

The version number might be different, but it will be equal to or higher than the one here. If you get any other output, check again to see if Node.js is set up correctly and try again. Hopefully, there won’t be any issues.

Now we need to set up a project where we will mainly convert ES6 code to ES5. Create a folder/directory where you want to keep this project, and from there, set up the project in your command line with this command. For example, I have created a folder/directory on my Desktop named `es5toes6` and then navigated to that folder/directory using the command line:

“`bash

cd es5toes6

“`

Now we will set up our project here:

“`bash

npm init -y

“`

That’s it; the project is set up. Now we need to install Babel CLI like this:

“`bash

npm install -g babel-cli

“`

If you are using Linux or any other operating system, you might need to use `sudo` before this command.

Then we need to install another dependency (or you can say a helper for babel-cli) like this:

“`bash

npm install -D babel-preset-env

“`

After this is installed, we will create a file named `.babelrc` in our project directory. Note the dot before the file name; it’s a hidden file, so you might not see it directly. However, you will find it with your code editor, and open it to write the following code. This is just a configuration:

“`json

{

  “presets”: [“env”]

}

“`

Here’s the translation of the provided text from Bengali to English:

So, all our configurations are done for now. Now we’ll write some ES6 code in a .js file. I’ve created a file named `script.js`, and inside, I wrote some ES6 code:

“`javascript

const name, age = 21, ‘Zonayed Ahmed’, work = ‘Student’;

console.log(“My name is $(name) and I’m ${age} years old! Currently I’m a ${work}”);

constaArrowFunc = () => {}

const sum = 10 + 20;

console.log(sum);

class Child6 {

  constructor(name, dob) {

    this.name = name;

    this.dob = dob;

  }

  currentAge() {

    console.log(“${this.name} is ${2018 – this.dob} years old!”);

  }

}

“`

Now we’ll convert this to a file named `script-es5.js`. For this, we need to give the following command in the command line:

“`

babel script.js -o script-es5.js

“`

Here, we’ve given the `babel` command, followed by the file we want to convert and then the name of the converted file. When you press enter with this command, you’ll see a new file named `script-es5.js` where your code has been converted to ES5.

Now, we might want the code to be written and automatically convert and update the ES5 version of the file. For this, we need to add another option to Babel like this:

“`

babel –watch script.js -o script-es5.js

“`

After giving this command, you will see that the command line is waiting. Now, as soon as you write ES6 code and save it, your changes will be saved in the ES5 version file. You won’t have to manually give commands to convert repeatedly. By using –watch, you will give the command, write code, save it, and it will be automatically converted immediately:

“`shell

C:\Users\Zonayed Ahmed\Desktop\es5toes6 (es5toes6@1.0.0) A babel –watch script.js -o script-es5.js

“`

change script.js

That’s it, in this way you can automate your development process significantly. By learning Node.js, you can do many more powerful tasks like this or even more.

Post Comment