Difference of '' and ''

2

I'm reading ng-book 2 on Angular 2 and in one of the exercises a question arose. When setting up my first code component it does not display the title and link values in the console, but the second works perfectly.

The first one uses single quotation marks. ''. The second uses accentuation, . What's the difference and why not?

// Não Funciona    
addArticle(title: HTMLInputElement, link: HTMLInputElement): boolean{
        console.log('${title.value} ${link.value}');
        return false;
      }

// Funciona    
addArticle(title: HTMLInputElement, link: HTMLInputElement): boolean{
        console.log('${title.value} ${link.value}');
        return false;
      }
    
asked by anonymous 05.03.2017 / 15:34

2 answers

4

Strings defined with backticks / crases (') allow interpolation (embed expressions in the middle of the string without closing its delimitation and concatenating it with another string), multilines of the line within the string or concatenate two strings in different rows) and parsing ( tagging / parse where you can use a predefined function).

This form of definition is native to JavaScript and is called template literals from ES2015 and template strings previously. ( link )

Examples of using template literals :

'texto' # simples 'string text'

'texto linha 1
texto linha 2' # multilinha equivalente a 'texto linha 1\ntexto linha 2'

'texto ${variavel} texto' # interpolação

function tag(literais, ...expressoes) {
    let resultado = "";

    for (let i = 0; i < expressoes.length; i++) {
        resultado += literais[i];
        resultado += expressoes[i].toUpperCase();
    }
    resultado += literais[literais.length - 1];

    return resultado;
}

tag 'texto ${variavel} texto' # parse
    
06.03.2017 / 19:13
3

In both TypeScript and JavaScript from ES2015 you can use the delimiter of backtick .

With it the string is now rendered, so you can place code expressions inside the string , and you can continue it on the next line, ie it does interpolation of string .

So the first one works, it just does not do what it expects. With normal quotes this is a text like any other, it does not interpret as a snippet of code to be executed.

    
05.03.2017 / 15:48