ES6 essentials for Angular

ES 6 essentials for Angular


AngularJS’ successor Angular released officially in September 2016. This was a welcome news for front-end folks of the enterprise world as they could now pitch the awaited framework as a technology choice for their projects.

After quite a lot of comparisons and due diligence our team also decided to use Angular for our latest project. Being an opinionated framework was a plus for us since we are a large team with developers all around the globe. But there is an entry barrier which I observed that a lot of teams (including mine) tend to ignore in the glory/race of adopting Angular i.e. being fluent in ES 6 and Typescript fundamentals. Hence this post to only cover the most frequently used ES 6 features we came across while developing with Angular.

Overall ES 6 is a big leap and well awaited enhancement to support the ever evolving world of JavaScript. Amongst all the new features the spec brings to the language, below are few I find most popular:

Block Scopes

Until ES 5 var was the only way to declare a variable and it only mattered if you declared it within a function body. ES 6 introduces two new ways to define variables. Using the let and const keywords. These keywords literally introduce block scope {} to the language. This means that their scope can either be global or local to the block in which they are declared.

const

  • "const” is almost self explanatory which means that the defined variables value is never expected to change.
  • This holds true for primitive types in JavaScript except when the const variable is referring to an object.
  • A thumb rule to use constant is they should always be immediately initialised and not just declared.
  • However, you cannot declare constants at class level.

Below is an example of the constants behaviour:

ES 6 constants example

let

  • "let" is what you should always be using unless you require a constant.
  • let declared variables are also block scoped just like const
  • You can initialise a let variable optionally but in practice it is often done immediately.
  • Similar to const you cannot declare let variables at class level.
  • Due to the benefit/feature of block scoping let or const variables are not hoisted.

Template Literals

Enhanced support for string literals with super features like multi-line and string interpolation. This is especially handy when playing with Angular and would prefer to have the template inline.

  • Template literals must be enclosed within a back-tick ` instead of a single ' or double quote ".
  • String interpolation is only supported by enclosing the expression within a dollar sign $ followed by curly-braces {} like ${somevar.property}.
ES 6 Template literals example

Classes

Classes in ES 6 do not differ than the ES 5 constructor functions. Rather they offer more readability and pure syntactic sugar. Developers coming from strongly typed languages like Java, C# etc will find this syntax more easy and adaptable.

  • Just like a constructor function it is a common and good practice to always have the class name begin with uppercase letter.
  • It is a good practice to always have a constructor function in the class body. This is a place to define member variables as well.
  • Member functions do not need the keyword function for definition.
  • let and const variables cannot be declared at class level. Since all the content defined within the class body is actually defined on the prototype.
  • Classes can extend each other by using the extends keyword.
ES6 classes example

Default parameters

An extremely convenient feature and implicit shorthand for the old way of making a parameter optional. Example: var name = pname || 'ironman'; This allows the function parameters to be initialised with default values if no value or undefined is passed.

It is important to know that the default argument assignment is evaluated at the call time and hence should always contain references to literals, objects or functions which are already defined and available.

function boostPower(currentLevel, boostFactor = 0.5){
   return currentLevel += currentLevel * boostFactor;
}
boostPower(10, 1) // 20
boostPower(10)  // 15 since the default of 0.5 is used

Destructuring

Another very convenient and shorthand syntax introduced to extract multiple values from complex data structures like objects and arrays. It can be considered as inverse of defining multiple values at same time using object or array literals.

  • When using destructuring syntax the type on the LHS should match the RHS i.e. array = array and object = object.
  • When destructuring objects the property names referred on the LHS must match to the object referred on the RHS.
ES6 Destructuring example

Arrow functions

Also known as fat arrow functions => and are similar in syntax to Java 8 lambda expressions. It is a shorthand syntax for function expression and best suited for smaller function bodies. Used quite frequently with Angular and RxJS.

  • Arrow functions do not create their own this but rather pick from their surrounding or parent.
  • They cannot be used as constructors.
  • Parenthesis () are a must if passing more than one argument.
const evens = [2,4,6,8];
let squares = evens.map(x => x*x); // [4, 16, 36, 64]
let total = evens.reduce((x,y)=> x+y, 0); // 20, more than one input

Modules

Though not yet supported by all browsers, modules are a feature baked into the language which helps better code structuring, reuse and sharing across scopes. I personally find them similar to a package feature available in other languages. Just like a package is made up of a logical group of classes, an ES6 module should also contain variables, functions or classes forming a logical unit in a single file. ES6 uses the keyword export to make the members of a module visible outside the module/file.

  • ES6 modules are stored in files. Which means that a ES6 module is always made up of one file.
  • There is no explicit name syntax for a module. The name of the file is itself the name of the module.
  • A module can have multiple named export statement but only one export default statement.
  • Modules are singleton by design and imports are always hoisted.
  • File extensions should be omitted when importing modules.
ES6 Module example

The above mentioned features are a quick win to get started/familiar with Angular examples and code. However, I would strongly recommend to learn the various new features like spread operators, generators, symbols, object literals etc also available with ES6 and Decorators (ES7). Overall they bring more power to the language and us as developers.

Lastly, my sincere thanks to Dr. Axel Rauschmayer for his Exploring ES6 book and the MDN Web Docs team for their precise documentation. These two resources were a tremendous help in my ES6 learning journey.