ES2015 Babel String Interpolation not working with apostrophe (but does with double quotes)

HockeyJ picture HockeyJ · Jun 23, 2015 · Viewed 12k times · Source

I am using babel / grunt to learn some ES2015.

According to this post there is no real difference in Javascript between single and double quotes. i.e. 'test' and "test".

When trying string interpolation though, it seems there is an issue with babeljs (or more likely - me). What is wrong with the code below please?

According to this document, it seems both should work. There are no errors in the Chrome console.

Working Js:

var name = "Bob", time = "today";
alert(`Hello ${name}, how are you ${time}?`);

Transpiles to:

var name = "Bob",
    time = "today";
alert("Hello " + name + ", how are you " + time + "?");

Provides the expected result.

Failing Js:

var forename = 'bob', surname = 'test';
alert('hello ${forename} ${surname} - how are you?');

Transpiles to:

var forename = "bob",
    surname = "test";
alert("hello ${forename} ${surname} - how are you?");

and provides the following output:

enter image description here

Answer

CodingIntrigue picture CodingIntrigue · Jun 23, 2015

You're right, there is no different between ' and " when it comes to strings, but in order to do string interpolation, you must use backticks around your template string, e.g.:

ES2015

var forename = 'bob', surname = 'test';
alert(`hello ${forename} ${surname} - how are you?`);

Resulting ES5

var forename = 'bob',
    surname = 'test';
alert('hello ' + forename + ' ' + surname + ' - how are you?');

Babel REPL