#JS from Start- Template Literals (ES6)

in GitPlait2 years ago

JS FROM START.png

I have not been publishing the tutorial as planned because of many things I need to fix. But, I will ensure I finish everything as planned. We are still on the basic parts and they may not be so interesting but you need them to understand the process of using them and building. So, just stick to them.

I explained string methods and concatenation and I have many examples in the last post. Today, I will be talking about template literals. They are part of ES6 and compatible with all modern browsers so there is no need to compile down to any old browser. I don't consider that when I am working because only a really old person would consider old browsers now that we have many new fast browsers.

Let's start by defining some variables.

const name = 'Mike';
const age = 25;
const job = 'Web Developer';
const language = 'JavaScript';
const state = 'FCT';

When you start building some real apps, you would be inserting HTML from JS. So, you will be creating some HTML string with your data. We will do an example here. I will show the ES5 way of doing this and proceed to the ES6 which is the template string or template literals.

ES5

html = '<ul>' +
        '<li> Name: ' + name + '</li>' +
        '<li> Age: ' + age + '</li>' +
        '<li> Job: ' + job + '</li>' +
        '<li> Language: ' + language + '</li>' +
        '<li> State: ' + state + '</li>'+
        '</ul>' ;

Screenshot (310).png

This ES5 method is kind of a pain the ass. The template literals make things easy.

// ES6 way.

html = `
    <ul>
    <li>Name: ${name}</li>
    <li>Age: ${age}</li>   
    <li>Job: ${job}</li>   
    <li>Language: ${language}</li>   
    <li>State: ${state}</li> 
    </ul>
`; // Here you don't need to use quote, use back tick. 

Screenshot (311).png

That gives the same but much better and cleaner. We don't have to concatenate. You could do functions in them and other expressions. I have not talked about function so I don't want to include them here we will get there soon.

document.body.innerHTML = html;

cover image-tykee-03.png

Sort:  

Upvoted by GITPLAIT!

We have a curation trial on Hive.vote. you can earn a passive income by delegating to @gitplait
We share 80 % of the curation rewards with the delegators.


To delegate, use the links or adjust 10HIVE, 20HIVE, 50HIVE, 100HIVE, 200HIVE, 500HIVE, 1,000HIVE, 10,000HIVE, 100,000HIVE


Join the Community and chat with us on Discord let’s solve problems & build together.