Posts Tagged

ECMAscript 2015

Javascript String: ECMAScript standards

This is the second article highlighting some of the latest improvement issued in the most recent released of the ECMAscript for javascript string.

The first article covered classes and is named:  Javascript Class: ECMAScript standards.

Javascript String

String is one of the most primitive object and most used in any programming language. It the most recent ECMAscript releases (starting from the 2015), javascript string have received some updated and improvement that will support developers in their usage.

This article will cover changes like templates literals, replacements, concatenation and tagged templates literals by offering brief descriptions and code snippets where appropriate.

Template literals

Template literals also known as “template strings”, can be accessed by the use of the back-tick (`) characters, differently from the basic strings that are initialised with single or double quotes.

This are very powerful as they enable string manipulation without the overhead that that we have had to use until now. The first feature of template literals that we are going to cover is the ability to specify multi-line strings.

Multi-line String

Javascript multi-line string have until recent being defined by ending the string with “/n” and a “+” sign, Like the example below.

old multi-line
 
console.log('This is my first line 1\n' +
'and this is my second');

This code, even if probably quite easy to write, it is not easy to maintain and not nice to read (breaking one of the rule of clear code).

If declaring a string with template literals notation, you will actually be able to define multi line string without the need of any additional character. The example below will actually output the same as the one previously shown.

Template literals multi-string
 
  1. console.log(`This is my first line 1
  2. and this is my second`);

String replacement “embedding”

String embedding or replacement occurs when we try to dynamically create a string by adding an expression or a variable within it. This is personally one of the feature that I really hate in Javascript. Most of the common languages had string manipulations methods and finally, this feature are also available to the Javascript developers.

Prior to the template literals you may have use the following to create a dynamic javascript string.

expression interpolation
 
var a = "Fifteen";
var b = 5;
console.log(a + 'is ' + (b * 3) + ' and\nnot ' + (b * 2) + '.');
// "Fifteen is 15 and
// not 10."

The above is not only quite tricky to write as it require lots of parenthesis and quotes, but it is also very hard to read compared to the following, that as with all the other examples, will output perfectly the same.

template literals: expression interpolation
 
var a = 'Fifteen';
var b = 5;
console.log(`${a} is ${b *3} and
not ${b * 2}.`);
// "Fifteen is 15 and
// not 10."

 Tagged template literals

This is an advanced for of template literals. It will enable you to create a function that can be used to parse you template literals.

The return value of this function does not have to be a string, but in the following example we show the “basic” feature.

tagged template literals
 
function tagExample(strings, valueOne, valueTwo){
    //the strings is the array of strings, each item separated by one of the value
    let firstPart = strings[0];
    let secondPart = strings[1];
    let thirdPart = "";
    if(valueOne >= valueTwo){
        thirdPart = "therefore younger than me."
    }else{
        thirdPart = "therefore older than me."
    }
    return `${firstPart} ${valueOne}
    ${secondPart} ${valueTwo}
    ${thirdPart}`;
}
tagExample`I am ${myAge}while my brother is ${myBrotherAge}`
//OUTPUT
"I am  15
while my brother is  30
therefore older than me."

String prototype methods

The following paragraphs are going to cover useful methods that have been released since the ECMAscript 2015.

javascript string includes

This new method is surely going to put a smile on your face. As a developer, I have used the following OLD method many times, and every time I had to go through over at least twice to make sure that it was returning the correct behaviour.

The include method will allow you to search for a specific string and will return the position. This was previously done using the indexOf() method like the example below.

indexOf
 
var stringToSearch = "This is a very long string";
stringToSearch.indexOf("string") !== -1;
//true

We are now able to easily obtain the same result using the includes() method. This method also allows us to pass a second paramether that specifies where the string starts.

string.includes()
 
var stringToSearch = "This is a very long string";
stringToSearch.includes("string");
//true

javascript string repeat

The name of this method is self explanatory. It allows you to repeat a specific string for a X number of times

string.repeat
 
let var1 = "etc ";
var1.repeat(3);
//etc etc etc

javascript string startsWith and endsWith

This helpers return a Boolean value and also support a second parameter that is the position to where the string check starts.

string.startWith
 
var string1 = "Start with a simple word and finish with another.";
string1.startsWith("simple ", 13);
//true
string1.endsWith("Start");
//false

Browser support

At time of writing, the features covered in this article are largely supported in all the main used browsers ( includes mobiles browsers), with the only exception of IE11 and is still not supporting this features as showed by the graph below or as it can be found in by following this link to caniuse.com website.

teamplate literals
teamplate literals

Conclusion

Even if the above feature may not be the most exiting introduced by the ECMAscript standards, they are surely going to make your day to day life a lot easier. Productivity can surely increase and this small methods will not only make you develop faster, but will also make your code more readable that is what most of us hope to achieve.

Javascript Class: ECMAScript standards

 Javascript class

Using javascript class will really improve your code readability, structure and making it shareable with others. ( see my other post: Coding standards: Meaningful Names in Javascript).

For many back end developers, this post would have probably been written over 10 years ago, as classes have always been present in many programming language ( c++, c# and java, etc..). Classes in javascript on the other hand, have just recently been introduced in the ECMAScript 6 release of 2015 and have not yet hit developers keyboards.

This post is aimed aimed to give an introduction to classes and it does not go in many details.

ECMAScrips for Javascript and its advantages

JavaScript does not have the best reputation amongst coding languages, but finally after the long waited version of the ECMAScript standard and good browser support, there is some light at the end of the tunnel, and it is time to deep into the enormous amount of changes that made into the standards.

In recent years, JavaScript developers have been busy creating a multitude of “hacks” and libraries to help us fulfil lack of features that made it hard produce a clean and structured code.

In June 2015 the ECMAScript standards 6 have finally provided a multitude of improvement to one of the most used language in the world, followed by a much smaller release (ECMAScript 7 in June 2016).

ECMAScript 6, took over 4 years to reach our desks, but it didn’t fail to impress and with current browsers finally introducing support for most of the changes, developers are now ready to get their hands dirty and help to improve JavaScript reputation.

Browser Support

Browser support has recently made a fantastic improvement, giving us all a chance to start and implement the great majority of the ECMAScript standards, without worry.

At the time of this post being published (June/2107) the support on desktop is almost complete ( click for full support table):

Edge

FireFox

Chrome

Safari

IE11

As shown by the table above, the support on desktop browser is quite complete, except the odd IE11 with an unacceptable level of support below 15%.

For mobile the situation is quite similar:

Android

iOS

Chrome

Almost full support for the most common browser except on android where just a quarter of features are supported.

Classes Before ECMAScript 6

Even if Javascript class have not been precisely available, developers across the countries have implemented them by using functions, scope, prototype and many other method. This has lead to a multitude of different approaches being adopted by programmers, making the dream of having a possible “standards” a myth.

In this post we will start from an existing small “class” written before the ECMAScript 6, and then implement the newly introduced “classes features” to show the power and structure that they provide to your code.

The code below is an algebra helper for rectangles.

Rectangle
 
var rectangle = function(width, height){
    var self= {};
    self.width = width,
    self.height = height;
    
    var calculateArea = function(){
        var area = 0;
        area = (self.width * self.height);
        return area;
    }
    var calculatePerimeter = function(){
        var perimeter = 0;
        perimeter = (self.width + self.height) * 2;
        return perimeter;
    }
    var getHeight = function(){
        return self.height;
    }
    var setHeight = function(height){
        self.width = height ;
    }
  
  return {
    calculatePerimeter: calculatePerimeter,
    calculateArea: calculateArea,
    getHeight: getHeight,
    setHeight: setHeight
  }
};

Classes in ECMAScript 6

In this section we are going to update the above code to use the javascript class feature.

Class

The first thing that we will have to do is create a base class called rectangle.

base class
 
class rectangle{
    
}

Contructor

Then we will create a constructor. In the previous version of Javscript to emulate the constructor we would have had to create an init function or a self calling function within the method. ( none of this example is shown above as this cover the basic to assign some values).

javascript constructor
 
  constructor(width, height){
 this._width = width;
 this._height = height;
 }

Getter and Setter

Our class is starting to take share, we will now implement the GET and SET methods

Javascrtipt get methods
 
   get height(){
        return this._height;
    }
    set height(height){
        this._height = height;
    }

This methods have been introduced in the ECMAScript 2015. They are commonly used across different programming language and do not require a function call to be initialised. An example usage of the above would be:

get and set
 
var r = new rectangle(10, 5);
r.getHeight;// Output 5
r.setHeight = 10
r.getHeight;//Will output 10

Methods declaration

Class methods have not changed and the declaration is very similar to the one showed in the initial javascript example. The main difference to note is that every method declared within a function will actually be set to PUBLIC. There are rumours of the implementation of public variables and methods for the next ECMA release ( Javascript new private class field). There are currently 4 different “solution” to make standards private methods, and they are all out of the scope of this post.

Method declared within a class will not require the “function” word, and do not require to be returned or specifically made available as they will be available as part of the object immediately after initialisation. Our example will be:

class methods
 
    calculateArea(){
        var area = 0;
        area = (this._width * this._height);
        return area;
    }
    calculatePerimeter(){
        var perimeter = 0;
        perimeter = (this._width + this._height) * 2;
        return perimeter;
    }

Conclusion

This post is aimed at sparkling some curiosity, and give just a small definition of javascript class. The final result is:

final
 
class rectangle{
    constructor(width, height){
        this._width = width;
        this._height = height;
    }
    get getHeight(){
        return this._height;
    }
    set setHeight(height){
        this._height = height;
    }
    calculateArea(){
        var area = 0;
        area = (this._width * this._height);
        return area;
    }
    calculatePerimeter(){
        var perimeter = 0;
        perimeter = (this._width + this._height) * 2;
        return perimeter;
    }
}
var r = new rectangle(10, 5);
r.getHeight;// Output 5
r.setHeight = 10
r.getHeight;//Will output 10

Classes are maybe still not fully ready for big production environment ( mainly because of the absence of a private field), but we should start to use them to get confident in using them when time comes. There are still some amazing features like inheritance ( that has not been covered in this post) that make class worth using.

I personally like the use of class because they force to structure the code differently. They put a big distinction between normal functions and big chunk of work and are perfect to get around Object orientated programming.

I will keep posting my finding on the ECMAscript 6 and future release as for my opinion this is the real future of javascript.

"