Category

Javascript

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.

Phaser Game Part 1: Set up Node Js Server and PhaserJs

This post is part of a series of blog posts aimed to describe the step by step process of creating an browser game with PhaserJs using the latest ECMAscript standards.

This post in particular will set up the basic requirement for the game (server and file structure).

The Tech stack

For this game, I am going to use NodeJs and Express as our back-end server.  I usually use side project like this to gain experience on new territory, but this does not indicate that other servers may be less suitable.

Most of the game and all the game engine, are handled by the browser ( hence the name browser game) and therefore the Server does not play a key part and using nodeJs may actually be a good lightweight option.

The Javascript will be written using the latest ECMAscript 6 standards (please check current support from other blog post). This will enable us to investigate and lean the new standards, while developing the game. (Achieving two objects at once).

Set up the Work Station

Folder Structure

Game

->Server.js

->Index.html

->Assets //This will include all the images and sprites

->Js //This will include all the js file required for our game

->External //This will include the phaser.js library

NodeJs

To install node js you need to download the latest stable version from the Node.js download page. The installation process is quite simple and quick.

After installing node, we will then be able to install all necessary packages by using the NPM software registry, directly from the command prompt.

Express

The first requirement for our small server, will actually require us to install an NPM package called express. This package is one of the most comprehensive web application framework available for NodeJs. To install it you will need to enter the following in your command prompt window:

Install Express
 
cd c:/game/
npm install express

If you are not familiar with the command prompt, in the above snip of code we have firstly navigated to a specific folder, then run the “npm install” command specifiying the name of the package we wanted to install “express”.

This is all that is needed to install new packages using the NPM (Node Package Manager).

Code Editor

There is no requirement for  a code editor. PhaserJs can be ever be developer in a basic notepad.

For personal experience I would suggest one of the following:

  • Visual Studio Code
  • Atom
  • Sublime
  • Nodepad++

Basic Server

To create a web server using Node and Express we just need a couple of lines of code. More information can be found on the express website.

The following code need to be inserted in the file names Server.js.

Basic express server
 
//Example usage in the command prompt
//node Server.js
// Parameters
const port = 880; //Specify a port for our web server
const express = require('express'); //load express with the use of requireJs
var app = express(); //Create an instance of the express library
app.use(express.static(__dirname + '/'));//Serving static files
app.listen(port, function() { //Listener for specified port
    console.log("Server running at: http://localhost:" + port)
});

The code is heavily documented for illustration purpose. Please also note the use of the “const” type.

To run our server we just need to enter the following in our command prompt

run express server
 
node Server.js

Web page

Now that our server is now ready, it is time to create our first webpage.

To do so, just enter the following in the Index.html file:

Basic Index page
 
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
    <title>My Game with PhaserJs</title>
</head>
<body>
    <h1>Welcome to my game</h1>
    <p>This is my game page.</p>
</body>
</html>

PhaserJs

It is time to add the PhaserJs library in our folders. To do so, visit the phaser JS website. There are many ways to download the library, either by npm command, or by cloning the repository from Git.

After downloading the library, please place the minified file “phaser.min.js” in the external folder to have it ready to be used in our next post.

Conclusion

Our server is now running (by using the command above) and we can access out newly created server by accessing “localhost:880” in our web browser.

This post was needed to set the scaffolding for out game.

 

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.

Coding standards: Meaningful Names in Javascript

Intro

This post, is part of a series aimed at creating some basic coding standards for the javascript language.

Even if Javascript is well known for being “flexible”, giving the developers too much freedom when using it, it does not mean that there could not be a standard.

My personal speciality is Javascript, and like many developers, I started to use it adopting my code structure and implementation, depending to the project I was running, the pressure and sometime due to the weather ( I live in Wales, so the weather need to be mentioned!). But recently there have been two main event that have helped me to understand the importance of structure. Firstly  I have started to move toward a Full Stack position, starting to learn new languages and learning different techniques and then I was introduce to Clean Code: A Handbook of Agile Software Craftsmanship, one of the best book on the market for coding standards.

Even if I strongly suggest to read the book as it was very inspiring for me, I am still going to dedicate some of my blog post to analyse and migrate part of the book into the Javascript world, highlighting starting from the use of names.

Note: All the “Bad” examples below, comes from real life experience.

Summary from the book

I have extracted part of the book by quoting the most important sentence of the paragraph accompanied by a real life example. Some section have been omitted as not fully relevant with Javascript.

Use Intention revealing Names

The name of a variable, function, or class, should answer all the big questions. It should tell you WHY it exist, WHAT it does, and HOW it is used.Use Intention-Revealing Names

example 1
 
//Bad
var time;
var diff;
//Good
var todaysTimeInMilliseconds;
var ageDifferenceBetweenUsers;

Use pronounceable names

If you can’t pronounce it, you can’t discuss it without sounding like and idiot.Use pronounceable names

example 2
 
//Bad
var btn;
var usrAdd;
var psw;
//Good
var actionButton;
var userAddress;
var password;

Use searchable Names

If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly name.Use searchable names

example 3
 
//Bad
var dd;
var max;
//Good
var directDebit;
var maxAjaxAttempt;

Avoid Mental Mapping

Readers shouldn’t have to mentally translate your names into other names they already know.Avoid Mental Mapping

example 4
 
//bad
var fn;
var ln;
//good
var firstName;
var lastName

Note: If a loop is bigger than 10 lines, this should have meaningful names too instead than a 1 letter variable.

Don’t be cute

Choose clarity over entertainment value.Don’t be cute

example 5
 
//Bad
var theOnlyButton;
var killSwitch;
//Good
var submitForm;
var closeWindow;

Pick one work per concept

Pick one word for one abstract concept and stick with it.Pick one word

example 6
 
//bad
var fetch;
var retrieve;
var get;
//Good
//use just one across all the project.

Use solution domain name

Remember that people who read your code will be programmers.Use solution domain name

 

example 7
 
//Use technical terms:
var queue
var absolute
var length

Do it for your future self

It is always easy to quote a great artist, or to create a couple of examples, but the hardest part is to actually merge this small little tips in your everyday life.

I have seen an amazing improvement in my code quality and sharability ( ability to share my code with other developers without the need to add comment or explanation). I wanted to start and write this post to make people realise the importance of this small little changes.

Sometime we think that by using a very short variable we have saved ourselves time, but it is completely the opposite. The code that we have just written now, will be read many times, not only by yourself while developing but also down the line when the next update will be required in the future ( prob still you in 6 month time) or by a developer that will have no business knowledge, and that extra second that you have saved in naming a variable with a short name will be lost over and over again overtime.

Spending some extra time on deciding the correct name for a variable is worth every penny, sometime the best thing when in doubt is to ask a colleague, there is no one, better that someone that doesn’t know anything to support you in this hard task.

From practice to real life

I have written the following code to show a real life example and show how a few little variables can really change the speed with which we can read and understand the code. This is not to say that the code is actually perfect, but it is surely an improvement.

The following 11 lines of code, have nothing wrong. It is a normal function with a couple of “For loop”.

Lets read it:

Real Example 1
 
var updateObj = function(obj){
    for(var i = 0; i <= obj.length; i++){
        var sum = 0;
        for(var a = 0; a <= obj[i].marks.length; a++){
            sum += obj[i].marks[a];
        }
        var avg = sum / obj[i].mark.length;
        obj[i].exc = (avg >= 70) ? 'Yes' : 'No';
    }
}

Was it easy to read, does it explain what it does since the start?

Well, this is what most people code will probably look like. I have probably created an extreme case, but many of the pattern in the above code can be found everywhere ( the user of updateObj as variable name, or name a variable sum because is s sum of number).

The same code, with a little clean up on around names will look something like:

real example 2
 
var addExcellenceFieldToStudentsObj = function(obj){
    var students = obj;
    for(var i = 0; i <= students.length; i++){
        var student = students[i];
        var sumOfCurrentYearMarks = 0;
        var numberOfMarks = student.marks.length;
        for(var a = 0; a <= numberOfMarks; a++){
            var mark = student.marks[a];
            sumOfCurrentYearMarks += mark;
        }
        var finalMarkAverage = sumOfCurrentYearMarks / numberOfMarks;
        student.excellence = (avg >= 70) ? 'Yes' : 'No';
    }
}

The function main login is still the same, and the two For Loop are still there, but not there is a different flow when reading the code.

You don’t need to arrive at the end of the function to know that we are working on the studentObject ( the function name is now easily searchable), and you don’t need to reach the tenth line to understand that by sum we mean sum of mark.

Conclusion

This is just a small example of the power of naming. If used properly it can really change the way we develop and the way people see our code. It increase quality, readability and remove the need of comments (that are not needed if a code is well written).

I am astonished by the amount of time I have spent time reading a code over and over to understand what i really does before being able to change it, and even more surprised when that code was written by myself. I have since when making sure every file I create or update will have the same kind of “naming refactoring” showing above, as the effort is minimal ( it doesn’t change logic and if the test is covered by automatic test is quite a log risk change), but the improvement is enormous.

I hope you too share the same feeling and will help me create this standard across the industry to make Javascript a cleaner and more consistent language.

 

From Website to Mobile App

Progressive Web App

Progressive Web App is a collection of web technologies that is aimed at offering a fast, reliable and engaging  experience for application (progressive-web-app), even when the app is accessed offline.

This post is going to cover one of the technologies offered by the progressive app, the “Web App Manifest”.

The manifest is very powerful, because even if  simple to implement and deploy on your website, it will actually enhance the user experience, making your website look like a native application, by making it accessible straight from the home screen without the need to be downloaded from any AppStore.

Unfortunately as every new trend used accross the web, the support of this functionality is still quite low, but recent adoption of this in chrome and Firefox have made this feature worth learning (web-manifest-support).

The manifest file is accessible by anyone from the debugger tool offered by chrome within the Application tab. This tab is also used for other Progressive Web App feature like the service worked.

manifest from debugger
twitter manifest from chrome debugger

How to include a manifest

A manifest, as mentioned above, is just a simple json file that will include basic information about your app. The file can be added in your website like any other resource, by being referenced in the page header within a link tag.

link
 
<link rel="manifest" href="/web-manifest.json">

 

The manifest Details

The manifest does not require all fields to be filled in, in fact in this post, we are going to cover what we believe to be the most common arguments.

The minimum requirement of  a manifest file are name, description and a single icon.

Name and description

The first fields are off course the core of our app, and cannot be anything different that name and description. This give basic details about the app (description), and are used as label for the icon (name).

name
 
"name": "MyApp",
"short_name": "MyApp",
"description": "This is my app and is amazing!"

Icons

The icon section is probably one of the most important and required field for the manifest. It specify the location of all different icons, divided by size and density.

Currently there are 6 different icons sizes in the mobile world and they are 48px, 72px, 96px, 144px, 168px, 192px.

The example below will cover just one icon example, but for best result across devices all of the above should be covered.

icons
 
  "icons": [{
    "src": "images/touch/icon96.png",
    "sizes": "96x96",
    "type": "image/png",
    "density": 2.0
  }]

background_color

This is an interesting field, that when used, will give your app a nice touch.

The background color specified in this field will be applied to the app on click, before the stylesheet is loaded. If used correctly ( so for example if the colours are different from this field and the real background), it will notify when the app is loading.

The color can be specified directly with a supported color name (red) or the or by HEX color code (#333).

background_color
 
 "background_color": "#333"

display

This is the field of excellence, this setting will increase the user experience by giving you the ability to open the app fullscreen removing any browser interface.

The display field can accept four settings (fullscreen, standalone, minimal-ui, browser).

The fullscreen value is what provides the app the native look we have all been waiting for.

display
 
 "display": "standalone"

related_application

If you are reading this post, the filed below will most likely not fit your need. But it was too important to be left out.

The related_application array, will inform the mobile device, that there is a native application with a specific link to the AppStore.

related_applications
 
 "related_applications": [
  {
    "platform": "play",
    "url": "https://play.google.com/store/apps/details?id=com.example.myapp",
    "id": "com.example.myapp"
  }]

When the a related native app is available, and if the app provides additional feature from the Progressive Web app, then the user car be notified that the native app is preferred with the following field. This should be avoided if both the website and the app offer similar features.

prefer_related_applications
 
"prefer_related_applications": true

others

There are many other settings, such as orientation, start_url, service_worker, lang. But I wanted to focus on the most important points and leave you the possibility to go and investigate further what the manifest and the Progressive App technology has to offer.

The manifest is still in draft, but due to its progress in browser support and wide use across the internet, is surely going to make is way to the standards soon.

Reference

Main image from: http://marketingland.com/

W3C manifest proposal: https://w3c.github.io/manifest/

"