Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 542
JsAndDotNet Avatar asked Jun 23 '15 10:06

JsAndDotNet


1 Answers

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

like image 93
CodingIntrigue Avatar answered Nov 20 '22 16:11

CodingIntrigue