The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Combining Strings and Variables

by kirupa   |ย ย  filed underย JavaScript 101

Learn how to combine strings made up of static text and variable values using both the concatenation and template literal approaches.

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.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design ๐ŸŽจ, development ๐Ÿค–, and business ๐Ÿ’ฐ - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Serving you freshly baked content since 1998!
Killer icons by Dark Project Studios

Twitter Youtube Facebook Pinterest Instagram Github