FORUM Menu

Combining Strings and Variables

by kirupa   |   filed under JavaScript 101

Ah, yes - it’s time for us to look at the ancient art of combining strings and variables where we generate a string made up of both literal (static) text values along with variables whose values are defined as a result of some JavaScript operation. This is an important topic for us to look at, for we will find ourselves combining strings and variables quite often - whether it is for printing messages to the console, specifying a key to some Object, generating a complex CSS property value, or trying to accomplish a boatload of other things.

In the following sections, we’ll look at the two best approaches we have in JavaScript for combining strings and variables. This is going to be a hoot!

Onwards!

Our Setup

To help highlight the two approaches, let’s work with an example. For this example, we are going to have a function called sayGreeting, and it will take three arguments - one argument for the greeting, one argument for whom the greeting is targeted to, and one argument for an emoji to display. This function's signature will loosely look as follows:

If we call our sayGreeting function with the arguments Hello hello hello, Police Officer Panda, and 🐼, what this function will return is a string that looks as follows:

Hello hello hello, Police Officer Panda! How are you? 🐼

Notice that some of the words in the greeting are based on the arguments we passed in. Some of the words are provided by the function itself. And with this, it's time to look at what exactly goes on inside our sayGreeting function.

Using the + Operator (aka String Concatenation)

An approach as old as time for combining strings is one where we combine (aka concatenate) each string fragment using the + operator. Take a look at the following:

function sayGreeting(greeting, who, emoji) {
  let message = greeting + ", " + who + "! How are you? " + emoji;
  return message;
}

let batman = sayGreeting("Good morning", "Batman", "😀");
console.log(batman); // Good morning, Batman! How are you? 😀

Notice how we combine the values of the greeting, who, and emoji arguments with some of our predefined text to generate the final message:

function sayGreeting(greeting, who, emoji) {
  let message = greeting + ", " + who + "! How are you? " + emoji;
  return message;
}

Each literal text value is separated using quotations marks. We use the + operator to stitch together these literal text values and variables together into one final string, which is stored by message. The spaces and punctuation marks that make up our final greeting are explicitly (maybe awkwardly?) defined as well.

Now, what we have here is a fairly simple example. For more complex strings made up of a bunch of variables and literal values, the number of + operators and quotation marks can become quite large and unwieldy. If we are printing text that itself has quotation marks and special characters, we need to take extra care to escape them to ensure the final string is still valid. With this concatenation-based approach, this isn’t the sort of stuff that we write and have working properly on the first try...at least not for me!

Template Literals (aka String Interpolation)

A more modern approach involves using what are known as template literals. With template literals, instead of using the + operator to combine each string fragment, we define the full string up front and mark the areas where we need to substitute a value dynamically. This will make more sense with an example, so what we have below is another version of our sayGreeting function, this time using template literals:

function sayGreeting(greeting, who, emoji) {
  let message = `${greeting}, ${who}! How are you? ${emoji}`;
  return message;
}

let panda = sayGreeting("Hello hello hello", "Police Officer Panda", "🐼");
console.log(panda); // Hello hello hello, Police Officer Panda! How are you? 🐼

Notice what is going on here. First, we define the full string, but we don’t designate it as a string by wrapping it using quotation marks. Instead, we use the mysterious backtick character ( ` ) which is to the left of the number 1 key on most of our keyboards:

The backtick characters tell JavaScript that everything inside them should be treated as a string. Next, for the places where we need to insert or substitute a dynamic string value, we designate those placeholders by using the ${expression} syntax. At runtime, the value of ${expresion} is turned into a string whose value is whatever we put inside it. Typically, what we would have for our expression are just the variables, but our expression can be any combination of JavaScript-ey things like function calls, string methods, and more. We'll keep things simple and focus just on variables here, so putting this all together, our code for generating our message looks as follows:

function sayGreeting(greeting, who, emoji) {
  let message = `${greeting}, ${who}! How are you? ${emoji}`;
  return message;
}

All of this is accomplished without the error prone process of breaking up our string using + operators and inserting a series of opening and closing quotation marks around our literal string values. By working with our final string output and using placeholders, this approach is also more readable. This makes substituting some text values from a large and complex string a piece of 🍰!

Conclusion

We have two (good) approaches for combining literal strings with variables:

  1. String concatenation using the + operator
  2. String interpolation using template literals

The all-important question is, which one should we use? Unless you are dealing with something really trivial, I would shy away from using the string concatenation approach. It gets really error prone when you have many series of string fragments that you need to deal with. Also, getting all the quotation marks and spaces right is too time consuming. Combining strings using the template literal approach is quite good for almost any scenario because of how readable the code is. This readability comes in quite handy for both simple cases as well as more complex cases as highlighted across many articles on the site.

What we also have in JavaScript are a handful of other ways to combine strings with variables. We have the concat method that lives on the String object, we have Array.join, and a few more esoteric approaches. These approaches aren’t very good, so I won’t bore you with details about them. If you really want to know more, post on the comments below.

Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you'll ever run into will be happy to help you out!

When Kirupa isn’t busy writing about himself in 3rd person, he is practicing social distancing…even on his Twitter, Facebook, and LinkedIn profiles.

Hit Subscribe to get cool tips, tricks, selfies, and more personally hand-delivered to your inbox.

COMMENTS

Serving you freshly baked content since 1998!
Killer hosting by (mt) mediatemple

Twitter Youtube Facebook Pinterest Instagram Github