JavaScript Basics #8: Strings

JavaScript Basics #8: Strings
Jan Zavrel
Jan Zavrel Follow July 02, 2021
Share:

In the previous article, we assigned a string to a variable (let myName = 'Jan';). Now, let’s see how to concatenate and interpolate strings.

Concatenation

Concatenation is a fancy word for combination, and it’s performed with a + operator. It allows us to combine two string values even if they are stored in variables:

let myFavoriteBrand = 'Apple';
let myNotebook = 'MacBook Air';  
console.log('My favorite brand is ' + myFavoriteBrand + ' and I love my ' + myNotebook + '.');  
// This will be printed to the console: 'My favorite brand is Apple and I love my MacBook Air.'

In the example above, I assigned the value 'Apple' to the myFavoriteBrand variable, and the value 'MacBook Air' to the myNotebook variable. On the third line, I used the + operator combine four strings: 'My favorite brand is ', the value saved to myFavoriteBrand, ' and I love my ', the value saved to myNotebook, and '.'. I logged the result of this string concatenation to the console as:

My favorite brand is Apple and I love my MacBook Air.

Notice that you need include spaces at the beginning and the end of each part of text before you combine it with variables, without it, the program would lump it all together, because it doesn’t understand a separate words.

Interpolation

As you can see, concatenation can be quite tedious. That’s why modern JavaScript allows you to insert (interpolate) variables into the strings with template literals.

I rewrote the code above with interpolation, and here’s the result:

let myFavoriteBrand = 'Apple';
let myNotebook = 'MacBook Air';  
console.log(`My favorite brand is ${myFavoriteBrand} and I love my ${myNotebook}.`);  
// This will be printed to the console: 'My favorite brand is Apple and I love my MacBook Air.'

As you can see, this code is far easier to read and understand. Notice that a template literal is wrapped by backticks (`) instead of single quote ( ' ). Inside the template literal, we use a placeholder ${} and insert the value of the variable into it.

Since we don’t use quotes to wrap our content, we don’t have to worry about escaping them (more on that later).

Follow me on Medium, Twitter, Facebook and YouTube.

Share:
Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.