ES6 Everyday: Template Strings

I’m pretty pumped about this one.

ES6 introduces template strings, delimited by back ticks:

var message = `Order submitted.`;

console.log(message); // Order submitted

I know, I know, nothing exciting yet. But check this out: with template strings, you can now have multiline strings:

var message = `Order submitted.

Thank you for submitting your order!`;

Not only that, the real magic of template strings is string interpolation:

var orderNumber = "5678";
var message = `Order ${orderNumber} submitted!`

console.log(message);
// Order 5678 submitted!

And string interpolation doesn’t just stop at swapping out simple variables; you can stick code in there too:

var orderNumber = "5678";

var price = "10";
var quantity = "3";

function getCustomerName()
{
  return "Abraham Lincoln";
}

var message = `Order #${orderNumber} submitted for \$${price * quantity}.

Thank you, ${getCustomerName()}, for submitting your order!`;

console.log(message);
// Order #5678 submitted for $30. Thank you, Abraham Lincoln, for submitting your order!

Give it a spin for yourself in this ES6 Fiddle

Resources