ES6: Template strings

template strings

Quick post about template strings. If you are learning Ecmascript 6, you should read this post. This is the new way to embed variables in texts.

About

Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings

Template strings are enclosed by the back-tick (` `). So if you don’t have been using the back-tick, you should find it now on your keyboard, it will be very used from now.

To embed a variable in a text, you need to indicate it by the Dollar sign and curly braces (${expression}).

Examples

Syntax

'use strict';

let age = 23;

console.log('I am ' + age + ' years old.'); // normal strings

console.log(`I am ${age} years old.`); // template strings

Multi-line strings

'use strict';

// normal strings

console.log("my text line 1\n" + 
"my text line 2\n" + 
"my text line 3\n" + 
"my text line 4\n");

// template strings

console.log(`my text line 1
my text line 2
my text line 3
my text line 4`);

Expressions

'use strict';

let a = 13;
let b = 10;

// normal strings

console.log("I am " + (a + b) + " years old and not " + (2 * a + b) + ".");

// template strings

console.log(`I am ${a + b} years old and not ${2 * a + b}.`);

Conclusion

Template strings are already being used and will be used more and more. So if you’re not used to it, get used to!
For you who is studying Ecmascript 6, take a look: https://github.com/airbnb/javascript (Airbnb JavaScript Style Guide)

Javascript Hoisting

hoisting

In the previous post, I wrote about strict mode in Javascript and how it is beneficial and helps you to write a better code. For example, to do not forget to declare a variable.

But, did you know that in Javascript you can declare a variable after accessing it?

Hoisting

In JavaScript, functions and variables are hoisted. Hoisting is JavaScript’s behavior of moving declarations to the top of a scope (the global scope or the current function scope). https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Examples

Variable

'use strict';

x = 'Declaring a variable after using it.'; // It works!
document.write(x);

var x;

Function

myFunction(10); // It works!

function myFunction(x) {
    console.log(x);
}

Cool. You’ve just seen that you can declare variables and functions after accessing them.

Ecmascript 6

Everybody is talking about Ecmascript 6, right? What about changing the example above from var to let and also make an example with class? It should work, right? Let’s see!

let

'use strict';

x = 'Declaring a variable after using it.'; // ReferenceError
document.write(x);

let x;

As you can see, let does not hoist the variable to the top of the block. You need to declare before using it.

class

var a = new myClass(1, 2); // ReferenceError

class myClass {
    constructor(x, y){
        this.x = x;
        this.y = y;
    }
}

Class declarations are not hoisted too. You first need to declare and then access it, otherwise code will throw a ReferenceError.

Conclusion

Hoisting is an unknown or overlooked behavior of JavaScript (to many developers). All you need to do to avoid bugs is always declare all variables at the beginning of every scope. Of course, always using the javascript strict mode. If you didn’t see my post about strict mode, check it out: http://blog.guinatal.com/javascript-use-strict/

JavaScript Use Strict

strict-mode

If you’re starting to encode javascript or you are already a javascript programmer and have never seen the strict mode before, check out this post.

About strict mode

I always recommend coding javascript in strict mode. Strict mode makes changes to normal javascript semantics. An important aspect is that the strict mode eliminates silent errors, forcing you to write a better code and don’t make mistakes.

Invoking strict mode

To invoke the strict mode, you just need to write ‘use strict'; in your javascript file, for example.

'use strict';

Now that you already know how to invoke strict mode, let’s see a quick example.

Quick example

'use strict';
foo = 'Guilherme'; // ReferenceError

You need to declare the variable.

'use strict';
var foo = 'Guilherme'; // It works!

Now it works!

Conclusion

As you can see, strict mode can help you a lot to write a better javascript code. If you wanna see more examples and know more how it exactly works, take a look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Working with currency in Javascript

currency_vs_javascript

These days I was developing in VB.NET. This application was working basically as a web service, and through the Javascript I made my asynchronous requests.

Everything was working fine, but I was working with currency. If you’ve already worked with currency, probably you should have had some problem. Especially if your backend project is set to a different culture type.

I am Brazilian, usually the projects that I work are configured as pt-BR. The response that I got from the web service was a currency setted to pt-BR. Examples: R$ 10,00 / R$ 1.000,00

Of course, I could just change the culture type of the web service return, it would make my life easier, but I hadn’t this option. I had to do everything in Javascript and I didn’t want to import a currency library.

Come aboard!

Currency to float

The first thing I needed to do is to create a function that would transform currency in a float.

function real2float(moeda) {
    moeda = String(moeda);
    moeda = moeda.replace("R$", "");
    moeda = moeda.replace(/\./g, ""); // it replaces all dots
    moeda = moeda.replace(",", ".");
    return parseFloat(moeda);
}
real2float("R$ 1.000,00") // 1000
real2float("R$ 974.430,30") // 974430.30
real2float("R$ 1.966.854,88") // 1966854.88

Now I could work with these numbers and make calculations. After that, I needed to transform these numbers in currency again to display them on screen.

Float to currency

To transform float to currency, I used the method toLocaleString.

“The toLocaleString() method returns a string with a language sensitive representation of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.”

function float2real(valor) {
    valor = parseFloat(valor).toFixed(2).toString();
    valor = parseFloat(valor).toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
        minimumFractionDigits: 2
    });
    valor = valor.replace("R$", "R$ ");
    return valor;
}
float2real(100.00) // R$ 100,00
float2real(500.29) // R$ 500,29
float2real(504440.93) // R$ 504.440,93

Conclusion

If you do work with a several types of currency in Javascript, could be a good idea to use some library. GitHub exists to help you to find good libraries and frameworks.
Or if you work with just one type of currency, I would recommend you to create manually 2 simple functions, like I did.
To know more about the toLocaleString method, take a look at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Javascript: querySelector vs getElementById

getElementById

I’ve realized that most of people usually don’t use the querySelector, thus I decided to write quick examples and the basic differences between querySelector and selectElementById as well as querySelectorAll and getElementsByClassName.

http://www.w3.org/TR/selectors-api/

Selectors, which are widely used in CSS, are patterns that match against elements in a tree structure. The Selectors API specification defines methods for retrieving Element nodes from the DOM by matching against a group of selectors. It is often desirable to perform DOM operations on a specific set of elements in a document. These methods simplify the process of acquiring specific elements, especially compared with the more verbose techniques defined and used in the past.

querySelector vs selectElementById

Let’s assume the following code:

<form id="userForm">
  <input id="username" type="text" value="Guilherme" />
</form>

We want to get the username element and allocate it in a variable. First let’s do this using getElementById.

var username = document.getElementById("username");

Now, let’s get the same element but this time using querySelector.

var username = document.querySelector("#userForm #username");

As you can see, using the querySelector the element that we want to select is much more specific and defined. The result is exactly the same.

getElementById image 1

querySelectorAll vs selectElementByClassName

Let’s assume the following code:

<form id="productForm">
  <input id="productOne" class="product" type="text" value="Product 1" />
  <input id="productTwo" class="product" type="text" value="Product 2" />
  <input id="productThree" class="product" type="text" value="Product 3" />
</form>

We want to get all the products elements and allocate them in a variable. First let’s do this using getElementByClassName.

var products = document.getElementsByClassName("product");

Now, let’s get the same elements but this time using querySelectorAll.

var products = document.querySelectorAll("#productForm .product");

The result is almost the same, but the getElementsByClassName returns a HTMLCollection and the querySelectorAll returns a NodeList.

getElementById image 2

Great! But these examples are very simple, so let’s try something a bit more difficult.

<table id="tableProducts">
  <thead>
    <tr>
      <th>Product</th>
      <th>Value</th>
    </tr>
   </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>100</td>
    </tr>
    <tr>
      <td>B</td>
      <td>200</td>
    </tr>
    <tr>
      <td>C</td>
      <td>300</td>
    </tr>
  </tbody>
</table>

In the example above, we have a table of products and we need to sum the values. I guess that there are some ways to do it, but let’s use querySelectorAll.

var sum = 0;
var cells = document.querySelectorAll("#tableProducts>tbody>tr>td:nth-of-type(2)");

for (var i = 0; i < cells.length; i++)
  sum += parseFloat(cells[i].firstChild.data);

Very simple, isn’t it?

Conclusion

The querySelector and querySelectorAll are really very powerful and work well when you need to select more specific elements. They are supported by most of current browsers. If you wish, here you can check the supported browsers: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Browser_Compatibility