ES6: string templates

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.

More posts