Posts Tagged

Standards

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.

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.

 

"