ECMAScript & its Features

ECMAScript is a term commonly used by developers for coding standard but most of us don’t know how did it come into the picture and why do we need it?
New Features in ECMAScript 2021 (with code examples) - DEV Community

Imagine a world without a set of rules for coding. Everyone would be writing their own codes, will have their own set of rules and when a new person enters the world of software development, he/she will never know which set of rules they need to follow. The situation will become chaotic!!

The same incident happened with Javascript. When Javascript was first created by Netscape then there was a war going on between all the browser vendors in the market. Microsoft implemented its own version of javascript in Internet Explorer and Mozilla implemented its own. Similarly, other browser vendors implemented their own versions.

All this created a huge problem for the developers. One version ran fine on Netscape but was a total waste on Internet Explorer or Firefox.

To solve the cross-browser compatibility, Javascript was standardized by the ECMA international and that’s the reason it got the name ECMAScript. All browsers eventually implemented ECMAScript (though it took a lot of time).

How is Javascript related to ECMAScript

JavaScript is actually the term most of the developers use for ECMAScript. Although there are other implementations available for ECMAScript like – JScript (Microsoft) and ActionScript (Adobe), but JavaScript has proven to be the best-known implementation of ECMAScript since it was first published.

Jeff Atwood (founder of Stack Overflow) coined the term “Atwood’s Law,” which states:

“Any application that can be written in JavaScript, will eventually be written in JavaScript. “

It’s more than ten years now, and Atwood’s statement still lingers on. JavaScript is continuing to gain more and more adoption. The “next generation” of Javascript is something known as ES6 (The 6th edition, officially known as ECMAScript 2015).

JavaScript==ECMAScript?. I'd like to begin this article by… | by Shreya Prasad | Medium

6th Edition – ECMAScript 2015

The 6th edition, officially known as ECMAScript 2015 is different because it introduces new syntax. Infact, a lot of new syntaxes.

Browser support for ES6 is still incomplete. However, we can still use ES6 features by using a pre-processor like Babel to cross-compile our JavaScript back to ES5 compatible code for older browsers, so there’s no reason to put off learning about it.

This update added arrow functions, promises, let and const, classes and modules and a lot of new features, but defines them semantically in the same terms as ECMAScript 5 strict mode. The complete list of new features can be found on http://es6-features.org

Learn ECMAScript 6 - Deep Understanding - Swiftcoding.com

Some of the new features that are introduced in ES6 –

Default Parameters

We do not need to worry about parameters taking 0 or undefined value since we can define defaults in the parameters’ list now. This also saves the overhead of sending parameters to each function call when we wish to use the defaults.

Block-Scoped Let and Const

‘let’ is a new ’var’ which restricts the scope of the variable to a block instead of the whole function. With ‘const’, things are easier. It’s just an immutable entity, and at the same time block-scoped like let.

Template Literals

It determines the way to output or append variables in a string. Now we have a simple bash-like syntax that makes the code look prettier.

Multi-line Strings

When writing a multiple line string, ES6 save a lot of typing efforts by its new syntax that uses ‘backticks’.

Destructuring Assignment

It provides intuitive and flexible destructuring of Arrays and Objects into individual variables during assignment so we do not need to write extra code for the assignment task.

Arrow Functions

Arrows are shorthand for functions using the => syntax. They are syntactically similar to C#, Java 8 and CoffeeScript arrows. Arrows would make your ‘this’ behave properly, i.e., ‘this’ will have the same value as in the context of the parent function – it won’t mutate.

Promises

Promises provide the representation of a value that may be made asynchronously available in the future. We can also combine one or more promises into new promises without worrying about the order of the underlying asynchronous operations.

Classes

ES6 provides more intuitive, OOP-styled and boilerplate-free classes. These classes encourage the prototype-based object-oriented pattern which brings support for inheritance, constructors, static methods and more.

Modules

ES6 includes a built-in module system which provides support for exporting values from modules and importing values to modules within the javascript code and without polluting the global namespace.

Spread Operator
The spread operator is an interesting way to build new arrays based on the values of existing arrays. It can:
  • Copy an array
  • Concatenate arrays
  • Insert new items into arrays

7th Edition – ECMAScript 2016

The 7th edition, officially known as ECMAScript 2016, was finalized in June 2016. New features include the exponentiation operator (**) and Array.prototype.includes.

Array.prototype.includes

The includes() method determines whether an array includes a certain element or not, returning true or false as accordingly.

Exponentiation Operator

The exponentiation operator works same as exponentiation in mathematics, it returns the result of raising first operand to the power second operand. For example – 5^10 or 7^12

Conclusion

There are a number of really great language-centric reasons to start writing your code in ES6 and ES7 now, but there isn’t enough room in a single blog post to enumerate them or go into the nuances of how they will make your life better.

Developing App? Here’s Angular Practices & Tips

Angular has been the most famous javascript framework among the developer community. It’s an MVC framework which provides pre-built components for developing the software application.Angular(2+) is based on Typescript , which is a superset of JavaScript. It comes with its most important advantage of static type checking that provides compile-time checking for any variable declarations and definitions.This blog is based around some best practices for Angular which I figured out while developing applications. There are also some bonus tips which I believe would help you with Angular development.

Essentials of mobile app development lifecycle that appreneurs must know - Business of Apps

Major Factors That Authenticate The Use Of AngularJS - Creative Tim's Blog

Follow the component based approach

Angular comes with the component-based paradigm which is also one of its best practices. It helps in maintaining modular and readable code.

While developing an angular code, if you think that something can be used multiple times as an independent piece of code, make it a component. A very basic example can be a simple dropdown which shows a list of options. The drop-down can act as an independent component with its own methods and template.

Few more examples could be – breadcrumbs for navigating throughout our web application, a simple alert box showing error/success messages or a loader. We tend to ignore these while thinking of modular approach but all these above examples can be thought of as independent components which can be reused over and over again.

Avoid using one huge global CSS

Angular’s current structure includes individual folder for every component. This folder includes-

  • .ts file for component logic
  • .html file
  • .css file for the component

So, keeping all of your CSS in one common CSS file would not only make your code less readable, it would make it less maintainable.

The best approach to style your components is to separate the global CSS with the local CSS (here local CSS refers to the component CSS). You should write your CSS in global CSS only when the CSS is written for the entire application and then if you need to style your component specific to a certain page, you can surely write in the local CSS.

Use CSS preprocessors for faster development

We can also use CSS preprocessors like SCSS/SASS for our Angular projects and I prefer them instead of writing plain CSS as they provide a lot of advantages over writing plain CSS. To mention one, the use of partials so that you can also separate your styles into multiple files for maintainability. If you guys want to know about partials, I would suggest you to go through this link.

You can divide your styling into multiple SCSS files just as we divide our application into multiple components. SCSS/SASS helps in writing smaller code which would ultimately get converted into CSS. So, why not save time and use it to our advantage.

CSS preprocessors | PSDtoWP.net

Save your time by using build tools

Tools like angular-cli have come up as a lifesaver for angular developers. It’s basically a boilerplate for an Angular application which helps in quickly setting up the angular application for your new project. It comes with all dependencies required for building your application and also has an inbuilt webpack which helps in bundling all your code and assets. Angular CLI helps to increase developers productivity through scaffolding by creating a component file, template file, stylesheet file etc. It comes with few basic commands which help in faster development like:-

  • ng g component my-new-component – it will create a new component with the name my-new-component.
  • ng g service my-new-service – it will create a new service with the name my-new-service.
  • ng g module my-module  – it will create a new module. A module is basically a collection of components which help to serve or attain a particular functionality.

Use ES6 paradigm and approach

Interfaces in Vanilla ES6 JavaScript – Full-Stack Feed

Though right now ES-8 is the current drafted version for ECMAScript but ES-6 came up with its own new features that are still widely used by developer community as they produce the same results with fewer lines of code and for best practices, every developer should know how to use them.

  • Arrow Function – In javascript, we use this keyword to refer to the current execution context. Previously, when we had to write javascript functions, this keyword would refer to the function context and we had to use a temporary variable to store the current execution context, so that we never lose it but with the arrow functions, the current execution context is never lost. For e.g., we could use an arrow function like this;

// ES5

var sum = function(x, y) { return x + y };

// ES6 (arrow function)

var sum = (x, y) => { return x + y };

Now, see the ES6 arrow function is just so compact and easy to understand and we can easily use this keyword inside this function to refer to the current execution context.

  • Template Literals – Template literals have come up with how we deal with printing strings having dynamic content.

For example, without template literals if we had to print a hello and goodbye message to a person, we would write something like :

const name = ‘AMAL’

console.log(‘Hello ’ + name +’ !’);

console.log(‘Goodbye ‘ + name + ‘ !’);

Now using template literals, it would be something like this:

const name = ‘AMAL’

console.log(`Hello ${name} !`);

console.log(`Goodbye  ${name} !`);

Now, who wouldn’t like to use the second syntax as it’s really easy to use and we don’t have to care about putting the spaces at right places so that the formatted output is correct.

Apart from these, const and let keywords came up as a replacement for global var variable so as to enable effective scoping of variables.

For a detailed overview of ES6 features, I would recommend having a glance over this.

Use Lazy Loading wherever possible

What is Lazy Loading | Lazy vs. Eager Loading | Imperva

Lazy loading is based around loading modules only when you want them to show.

We know about Angular’s modular architecture where a code is divided into modules with each module having its own components.

These components are basically views which might have some dynamic data. These components are rendered with the help of angular routing.

Lazy loading is one of the best things that angular framework comes with.

It’s based around one principle – ‘load/use it when you need it’. Oh, yeah what a lame
explanation I’ve given. There is a routing.ts file in every module which defines a URL for rendering each and every component.

Now when it comes to implementing lazy loading technique, what we do is we define a routing file for each and every module and we import each module only when the URL changes and it corresponds to rendering a component defined in the routing file of that module.

This technique requires a bit of patience to learn but take my words, it’s worth implementing. I can tell you with my personal experience; we reduced the loading time of our website by 3-5 seconds by implementing lazy loading.

Previously, we imported the whole bundle each and every time the user hit our website URL making our site slow while rendering. Then after implementing lazy loading, we only imported the module containing component required to render our index page and we just loaded other modules only based on what URL the user is switching to.

The Angular docs surely cover the lazy loading technique and it’s worth reading. You can check this link to learn more about it.

Follow DRY principle, extensively use services and directives

Services

DRY – This keyword is very famous in the developer community and it just stands for Don’t Repeat Yourself. So, when writing any code- be it Angular or any language- if you feel that you are basically writing or repeating the same code in every component, then you must pause then and there and rethink whether the code can be placed at a suitable place and can be shared by every component.

For example, if you want to call an API that updates user data, don’t call it in every component. What I would do it, I would rather make a service for it in the .service.ts file and would call that function whenever I need any component.

Also, it serves the purpose of using services in angular. Services help us in saving and fetching data and also help us write common functions which could be used by multiple components.

Directives

Now switching over to directives. A directive is a piece of code which is used to perform a specific task. Directives are of 3 types in Angular – component, structure, attribute.

  • Components are as we all know templates with logic to handle data.
  • Structure directives modify DOM by adding or removing an element.
  • Attribute directives change appearance or behavior of an element.

Once, I was wondering to restrict input elements to accept only numbers when a user types in for a phone number field which shouldn’t accept alphabets. For this, I built an only number directive which would only allow input elements to accept numbers through the keycode. So just by using this directive as an attribute on an HTML input element, I can modify/change its behavior.

Conclusion

Following best practice is never a compulsion. There are many ways of doing things and you may choose any path. However, using best practices mean that you are following a method or a technique which is tried and tested through experiments and has proved to be effective to attain desired results.

error: Content is protected !!