Ragmah
Ragmah

Reputation: 411

ES6 template gives a syntax error

I am trying my first steps in learning ES6 and right now am facing a few issues with templates.

JavaScript looks like this:

"use strict"

let name = 'John';

function makeUpperCase(word){
    return word.toUpperCase();
}

let template = '<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>';

document.getElementById('template').innerHTML = template;

It seems like my variables are not being read:

'<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>';

So when I load the page a see an error in my console saying Uncaught SyntaxError: Unexpected identifier

My index.html is as simple as this:

<html>
<head>
    <meta charset="utf-8">
    <title>Learning ES6</title>
</head>
<body>      
    <header>
        <h1 id="heading">Learning ES6</h1>
        <p>With Sidney de Sousa</p>
    </header>

    <div id="container">
        <div id="template">

        </div>
    </div>
    <script src="src/main.js"></script>
</body>
</html>

Am supposed to see a heading one saying: HELLO John Developer.

Hope you can help

Upvotes: 0

Views: 588

Answers (2)

JeanPaul A.
JeanPaul A.

Reputation: 3724

You are using the single quote ' hence it is interpreted as a string. (Also the string is being dissected when the function is used with value 'HELLO' - here the first ' is matched with the opening single quote - hence HELLO is treated as a variable in javascript, which is not defined.)

You should be using the back tick ` like this

let template = `<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>`;

Upvotes: 3

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

Are you sure that you are using backticks (`) instead of regular quotes (')?

Here is the example:

const str = `Hi, my name is ${userName}`;

Check out this link for details about template literals in ES6.

Upvotes: 1

Related Questions