Strings and Template Literals
Strings are a very important part of programming. Let's learn how to build strings using template literals. Consider the below code snippet:
const userName = 'Jacob';
const age = 32;
const job = 'Software Engineer';
const city = 'Paris';
We are now going to build a string based on the above variables. As we've learned in the previous lecture, we can use the plus sign to concatenate strings; let's put that to practice. We are going to write: I'm Jacob, and I'm a 32 years old Software Engineer living in Paris
.
There is one important thing I need to tell you before we create our string. If you get used to using single quotes to create your strings as I do, you must pay attention to what kind of string you want to write. If within your string or text you have words that contain an apostrophe or single quote like for example I'm, isn't, don't etc., you need to wrap your whole string between double quotes ( "I'm good!"
) else after the next apostrophe or single quote, JavaScript will consider it as the end of string.
const singleQuoteText = 'I'm good!'
If you try this, you will get a syntax error because JavaScript considers that your string ends after the second single quote .i.e. the quote after the letter I
. If you use VS Code, you'll notice that the color of the characters that come after the second single quote changes.
What you have to do to fix this error is to wrap the whole string between double quotes like this :
const singleQuoteText = "I'm good!"
That being said, to create our string here is what we are going to do :
const userIntro = "I'm " + userName + ", and I'm a " + age + " years old " + job + " livig in " + city + "."
console.log(userIntro)
You might be wondering from the above string concatenation; age is a number, and the rest of the things we're adding here are strings. So how does it work? This has to do with something called type coercion, which is a concept that we will talk about later. To make it short, JavaScript will convert this number ( age ) to a string to join it with the rest of the strings.
If you now reload your browser and look in the console, you will see that we are getting the expected string as output. You've certainly noticed that it's a pain to manage the spaces or keep track of how the sentence is structured. There is an excellent solution to that.
For complex strings like the one we just built, it's a pain to manage spaces, as I said previously.That's why starting with ES6; we have a much better tool to do this kind of stuff right now, which is called template literals.
With template literals, we can write a string more normally and then insert the variables directly into the string. Their corresponding values will then replace them. To make it short, a template literal can assemble multiple pieces into one final string. Let's have an example :
const userIntroLiteral = `I'm ${userName}, and I'm a ${age} years old ${job} living in ${city}.`
console.log(userIntroLiteral)
As you can see from the above example, to write template literals, instead of using single or double quotes, we make use of backticks ( `` ). We then use the dollar sign and curly braces ( ${}
), and inside the curly braces, we write the variable name. We can agree that using template literals is a much easier approach because all we have is a single string to handle. You also have to know that you can write any JavaScript expressions like a calculation between the curly braces, for example.
const currentYear = 2021
const yearOfBirth = 2000
const ageIntro = `I'm ${ currentYear - yearOfBirth } years old.`
console.log(ageIntro) // Result ==> I'm 21 years old.
If you now try to reload your browser, you will see the same result as before.
Now you know what template literals are and how they work in JavaScript, particularly in ES6. It's one of the most used ES6 features. It's amazing, and this will be useful in many situations. One thing to note is that we can also use template literals even if we don't insert any variable.
We can do something like this :
console.log(`I'm 21 years old.`)
and it will be perfectly fine. Many developers use this ( template literals ) for all strings because you don't have to think about which quotation marks to use; you just use backticks. If you need to insert any variable, it's much easier than going back and switching out the regular quotes.
Another great use case of template literals is to create multiline strings. Multiline strings were cumbersome to write before template literals. Here is what I mean :
/**
* Before ES6
*
* The \n means new line like in many programming languages just than in JavaScript
* You need to add one more \
*/
console.log("I'm Jacob,\n\
and I'm a 32 years old\n\
Software Engineer living in Paris.");
/**
* After ES6 with template literals
*
* All you have to do is to hit return or enter, and it will create a new line for us
*/
console.log(`I'm Jacob,
and I'm a 32 years old
Software Engineer living in Paris.`)
This will be very useful when we start building HTML from JavaScript. We will use these backticks to create multiline HTML elements and insert them onto a page dynamically.
Whenever you need a multiline string, always make sure to use template literals because it's a lot easier and cleaner.