Template strings in javascript (understanding ES6)

 Template strings in javascript (understanding ES6)

Template strings are basically the latest way of concatenating strings or be it functions and has come alive with the ES6 version of ecmaScript. So let us understand how we use Template String to concatenate or join two given strings before ES6 and once it has come:


<script>
    var FirstName = "Praveen";
    var MiddleName = "Kumar";
    var LastName = "Yadav";

    document.write(`${FirstName} ${MiddleName} ${LastName}`);
    console.log(`${FirstName} 
         ${MiddleName}
            ${LastName}`);


       // OLD WAY OF CONCATINATION OF STRINGS
       
    /*  document.write(FirstName + MiddleName + LastName);
        console.log(FirstName + MiddleName + LastName);
    */
</script>


OUTPUT:

template string in ES6
TEMPLATE STRING IN JAVASCRIPT ES6 VERSION


So with this example we understood that to use template string we have to use backlash followed by curly braces  `{}` and then we can concatenate any number of strings or values.In the above example we have been able to connect 3 values FirstName , LastName and MiddleName with the help of Template String.  Also when we are writing the code in console with the help of Template String we get the same amount of space and new lines inside console as much as we have used in the actual code. 


<script>
    var FirstName = "Praveen";
    var MiddleName = "Kumar";
    var LastName = "Yadav";

    function Names(a,b,c)
    {
        return `${FirstName} ${MiddleName} ${LastName}`;
    }

    var value = `HELLO Mr ${Names(FirstName,MiddleName,LastName)}`;
    
    document.write(value);
    console.log(value);
    
</script>

OUTPUT:

USING TEMPLATE STRINGS INSIDE FUNCTIONS


so, template strings has made our life easier and code less complicate.

Comments

Popular posts from this blog