In our starter files, open the index.html page from this lessons folder:
01.JavaScript Basics > 05.Mixing-strings-with-variables
This is completely possible with JavaScript, and there are different ways to do this. In the starter folder we have 2 variables in the index.html
file called name
and likes
:
const name = 'Chris';
const likes = 'pizza';
We may want to combine these into a sentence, and your first though may be to use the variable name in the string like this:
const name = 'Chris';
const likes = 'pizza';
document.getElementById('title').innerText = 'My name is name';
This will not work. Since this is all inside of the quotes, it is considered part of the string, and not read as a variable, and we will see My name is name in the browser.
Instead we need to break out of the string, and add or “append” the variable to the string, using the addition operator:
document.getElementById('title').innerText = 'My name is ' + name;
Notice the space at the end of the string. This leaves the space before the name. The string will now output as My name is Chris.
We can also keep going and add additional strings and variables together:
document.getElementById('title').innerText = 'My name is ' + name + ' and I like ' + likes;
There is also another way to do this which was introduced in ES2015. And this is to use template strings. Template strings involve using backticks, just like earlier when we used them to place text onto multiple lines.
First, remove the addition operators (plus symbols) and quotes:
My name is name and I like likes;
Then, wrap the full string inside of the backticks:
`My name is name and I like likes`;
The text is fine as it is, we can use this for regular text too. But if using variables, we need to wrap them with curly braces, and a dollar prefix:
`My name is ${name} and I like ${likes}`;
If we needed to store this, maybe to re-use it elsewhere, it can also be moved into a variable:
const name = 'Chris';
const likes = 'pizza';
const string = `My name is ${name} and I like ${likes}`;
document.getElementById('title').innerText = string;
And this all works as before, but this time all combined into a single string variable.