Construct strings with Template literals - ( Javascript )

Very often you need to concatenate (link) strings, numbers etc. together.

This is a typical example.

var multiLinedString = "The ball \n" + 
	var number1 = 10
	var number2 = 5
	console.log(multiLinedString  + "  " + (number1 +number2)  + " Times");

Notice I also need to use a newline tag “\n” to get a multi lined string.

This works. But it is cumbersome. It is also often the case that you end up with an error in there somewhere, an unclosed quote, a forgotten plus symbol and so on.

Annoying right.

Well say hello to : Template strings or also known as Template literals.

Note: Template string is old name for template literal.

Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

So before you go off to that link and read it ( recommended )

How do they help us to make less mistakes and less messing around in construction.

	var multiLinedString = `The ball
bounced `;
	var number1 = 10
	var number2 = 5
	console.log(`${multiLinedString} ${number1 +number2}   Times`);


Anything between a set of backticks will be typed as a string. (Thats typed as in it’s type)

This is cool because as you can see in the multiLinedString, I can just write normal multilines with no formatting or plus symbols, as long as they are surrounded in backticks.

But what about variables.

Variables need to be placed in a dollar bracket closure. ${ }

Anything in a dollar bracket will be treated as a var first before being tied to a string.
This means you can do maths with them first before they are typed to and become part of a string.

Have fun.


1 Like

InternetExplorer -> no Support?!

Good thing I don’t use it then… :smile: