Difference of ' ' and ` `

Asked

Viewed 1,047 times

5

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

The first uses simple quotes. ' '. The second uses accentuation, . What’s the difference and why it doesn’t work?

// 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;
      }

2 answers

7


The strings defined with backticks/crases (`) allow interpolation (embed expressions in the middle of the string without having to close its delimitation and concatenate it with another string), multilines (no need to escape a line break within the string or concatenate two strings into different lines), and processing (tagging/parse, where you can use a predefined function).

This form of definition is native to Javascript and is called literals template from ES2015 and from strings template formerly. (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals)

Examples of use of literals template:

`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

2

Both in Typescript and in Javascript from ES2015 it is possible to use the delimiter of backtick.

With him to string passes to be templates, so you can put code expressions inside the string, can continue it in the next line, that is, it interpolates the string.

So the first one works, just doesn’t do what you expect. With normal quotes that is text like any other, it does not interpret as a chunk of code to be executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.