String basics

We’ve seen how to create text in JavaScript using strings. And they can be made with either single quotes or double quotes. Any app you make will likely have lots of text, so we need to know how to work with those strings and manipulate them. For example, what if you want to combine multiple strings together?

Let's return to our previous example from the first lesson where we wanted to greet the user of our app. So we want to say in every case, "Hi," then add on the user's name:

let name = "Jane Doe";

The interesting thing about JS is that the traditional approach to combining multiple strings is the + operator, usually used to add numbers together. But the curious thing about the + operator is that if at least one of the values being added is a string, the plus operator (+) converts any non-strings to strings and concatenates or combines the result.

So let's try using it, we'll say the string Hi plus the name that's in the name variable and then log it:

let name = "Jane Doe";
let message = "Hi" + name;
console.log(message); // "HiReed"

So it works, but there's no space between the two words. It's all smushed together.

To fix this we have to add a space at the end of the first string like so:

const message = "Hi " + name;

Try to imagine if we many strings to concatenate in this example:

const message = "Hi " + name + ", how are you?";

You can see that it works, but it is hard to read, not intuitive to use a math operator for this, and easy to forget these spaces. Is there a better way?

Template literal strings

Instead of using quotes, either single or double to create this string, let’s use a new character called a backtick. The key is usually located above the tab button and it looks like this

This new string using backticks is what's known as a template literal and it makes writing concatenated strings a lot easier.

Instead of having to include quotes around every single strings we want to concatenate with the variable, we can delete them and wrap the entire expression in a set of backpacks:

`Hi name, how are you?`;

Now we can read this like a normal sentence, but in this case username will be read as a string and not as a variable. To execute JavaScript within a template literal, we use a special syntax. We take the bit of JavaScript that we want to resolve (in this case the variable username) and wrap it in this dollar sign and curly brace syntax:

const message = `Hi ${name}, how are you?`;

Now when we see our greeting, we get the same result, but in a far more straightforward, convenient and readable syntax.

${} can resolve any JavaScript expression

One more essential thing to note about the template literal is that the ${} syntax we used can resolve many valid JavaScript expressions and insert them into strings.

This is called string interpolation. So if you put a dynamically computed value inside a ${}, it is converted to a string and inserted into the string returned by the literal.

Say for example, we had a person’s weight and wanted to show their person’s weight on the moon. We could take that weight and use ${} to perform the calculation:

const weight = 150;
const moonWeight = `You weigh ${weight * 0.165} pounds on the moon`; // "You weigh 24.75 pounds on the moon"

This feature will be very helpful in later parts of the course where we’ll see how to put conditionals in template literals to conditionally show one or another elements to our app user. To do that, we’ll see how to use nested template literals--template literals within template literals

Template literals are improved strings

So as we see, in addition to concatenate, template literals are much more powerful dynamic strings.

  1. No more broken strings with template literals

To see this, let's ask the question--what happens if you try to use apostrophes or single quotes within a string created with single quotes?

'I'm a string'; // unknown: Unexpected token (1:24)

And what about for double quotes: what if you try to use double quotes in a string made with double quotes?

“He said,I am string.””

Both of these strings are broken, but there is a quick fix. We need to recreate the string with the other type of quote--

For a string made with single quotes, we fix it by changing it to double quotes and vice versa for the string made with double quotes:

"I’m a string";
'He said, "I am string."';

Or we need to tell JavaScript that it should ignore this quote characters within the string. We do that by what's known as 'escaping' the quote with a backwards slash :

'I\'m a string';
"He said, \"I am string.\"";

These two techniques are important to know, but if you want to always avoid this issue, use template literals and you’ll have no such issue if you want to use quotes of any sort in your strings:

`I’m a string`;
`He said, “I am string”`;

Template literals for more readable multi-line text

What if you want to text to span multiple lines? If you use ‘’ or “”, you have to include the \n or \r escape characters whenever you want a line break. These are called newline characters and carriage returns, respectively.

const threeLines = "This is a string\nthat spans across\nthree lines.";

This works, but if you had more text, you can imagine how annoying it would be to keep writing these characters for each new line.

In order to make code more readable, we can instead use template literal strings. These eliminate the need for concatenation or escaping on long strings containing newlines. The string as well as newlines will be preserved.

const threeLines = `This is a string
that spans across
three lines.`;

We'll still be using single and double quotes for basic string, but remember that if you want to manipulate your strings in any way, template literals are the best choice.