Ir para conteúdo

ES6: string templates

01/22/2016

Photo shows four newspaper boxes, probably Americans in residential neighborhood

Play with strings can often be something a little bit painful (you can also read boring இ_இ). This is due mainly to the fact of having to concatenate words/phrases with variables.

let author = 'Tiririca';
let word = 'Worse';

let oldMessage = word + ' than it is, it is impossible. - ' + author;

console.log(oldMessage);
// Worse than it is, it is impossible. - Tiririca

Strings templates for our happiness.

let author = 'Tiririca';
let word = 'Worse';

let message = `${word} than it is, it is impossible. - ${author}`;

console.log(message);
// Worse than it is, it is impossible. - Tiririca

My friend Rafael Rinaldi made a good point: you can use any kind of expression, not just variables.

const obj = {
  foo: 'bar'
};

const fn = foo => foo;

console.log( `${obj.foo}` );
// bar

console.log( `${fn('aloha')}` );
// aloha

Here you can find an JS Bin with the examples.

Do you like it? Did I write something stupid? Do you want to improve? Open an issue mentioning the post and let’s talk about it.

See all the posts