TOC
Data types:

Strings

Text strings, in programming usually just referred to as strings, are simply pieces of text. The ability to store text is obviously quite important in programming, just like numbers are, and JavaScript comes with a bunch of nice features to facilitate the use of strings.

In many programming languages, there are two data types for storing text: A char type, for storing a single character, and a string type for storing multiple characters. But in JavaScript, there is no char type - the string type is used no matter how many characters you want to store.

Defining a string

First of all, just allow me to show you how to define a string in JavaScript:

let s = "Hello, world!";

So, unlike a number, a text string is encapsulated between two quotes. In this case, I use double quotes, but in fact, JavaScript allows you to use single quotes as well:

let s = 'Hello, world!';

These two strings will appear the exact same way when used, so which type of quotes you use is mainly up to you.

Strings are basically arrays of characters

When a string is defined, you can access each character of it by its index, exactly as if you were working with an array (more on those later) of characters. The first character is index 0, the second is index 1 and so on. So, if we want to access the "w" of our string from the example above, we can simply do it like this:

let s = 'Hello, world!';
alert(s[7]);

I simply reference index 7, using the square brackets we'll use when working with arrays later in this tutorial, to get the "w" character from the string. This also means that you can treat a string like an array in other ways, e.g. loop through it:

let s = 'Hello, world!';
for(let i = 0; i < 5; i++)
	alert(s[i]);

Escaping quotes

When putting the string between a set of quotes, JavaScript knows where it starts and ends, so that it's not mixed in with the actual code. However, this also means that you have to pay special attention if you want to use quote characters inside your strings. For instance, how is JavaScript supposed to work with this example?

let s = 'Hello, world, what's up?'; // Syntax error

The answer is of course: It can't. It will think that the string ends after "what", because of the single quote right after it, but then the rest will result in a syntax error. For situations like this, there are two options: You can either mix quote types:

let s = "Hello world, what's up?";

...or you can use an escape sequence to let JavaScript know that the single quote inside the string is to be treated like a part of the string and not the end of it:

let s = 'Hello world, what\'s up?';

Notice the backslash before the single quote in the string - this is called escaping the character, basically meaning that we will take away the special meaning it normally has.

Special characters

We just saw how we could escape a quote, to remove it's special meaning, by prefixing it with a backslash. However, the forward slash can also be used in combination with other characters, to give them special meaning. A great example of this is the newline character, which inserts a new line in a string:

let s = 'Hello world,\n what\'s up?';
alert(s);

Notice the \n inside the string - it will be converted into a newline character, as you can see if you run the example. Another example of a special character is the \t, which will be converted into a tab (horizontal tabulation).

At this point, you may wonder: If the backslash is used to escape other characters, how do I insert an actual backslash into a text string? Well, you simply escape the escape character by adding one more backslash:

let s = 'Hello world \\ what\'s up?';
alert(s);

Template literals/strings

You would think that two types of quotes (single and double) would be enough to define strings in JavaScript, but in 2015, with the ES6 specification, a third type of strings was introduced. Instead of quotes, it uses backticks, and it comes with several cool possibilities not found in regular strings. Here's how it looks:

let s = `Hello, world!`;

Template literals, sometimes referred to as template strings, are not just about templates. They can definitely be used for that, as we'll see in a minute, but they are also just way more flexible than regular strings. For instance, they allow you to write strings that span multiple lines in your code:

let s = `A very, very
			long, long
			string...`;
alert(s);

But as you will see if you run this example, everything is indeed literal here - all characters are included, even tabs and multiple spaces.

Placeholders

Let's move on to the reason why it's called template literals/strings: Placeholders. In a normal string, if you wanted to mix static text with the content of a variable, it might look like this:

let w = "world";
let s = "Hello, " + w + "!";
alert(s);

We use simple string concatenation to build a string. But using template literals instead, we can mix static text with variables, like this:

let w = "world";
let s = `Hello, ${w}!`;
alert(s);

This is also called string interpolation - I can put a placeholder inside the string by using the $ notation, and it will automatically be replaced by JavaScript. This is especially handy if you have complex strings with many variables, where the previous approach (string concatenation) could look quite messy.

And it doesn't have to be a simple variable - everything you put inside the template literal, as a placeholder, will be evaluated by the JavaScript engine. Here's an example where I do math inside the string:

let a = 21, b = 2;
let s = `a * b = ${a * b}`;
alert(s);

Tagged templates

For even more complex use cases, we have something called tagged templates. They are mostly there to solve very advanced templating tasks, and are therefore not commonly used by most JavaScript programmers. Because they solve a complex task, they are also not as easy to understand as the regular template literals, so if you don't fully understand this next part, don't worry about it - you will probably not need it anytime soon if you are new to JavaScript.

Tagged templates allows you to specify a function that will be called when your string is interpreted, which gives you endless possibilities in string creation. You can use this technique by placing the name of the function directly before your backtick string, like this:

let s = Highlight`${name} is ${age} years old`;

When this string is interpreted, all elements of this string will be passed to a function called Highlight. When we implement this function, we get full control of how the result will look, allowing us to do pretty much anything before returning the result.

In my example, I want to add a set of HTML bold tags around each of the placeholder values. Here's the full example:

function Highlight(strings, ...highlights)
{
	let result = "";
	for(let i = 0; i < highlights.length; i++)
	{
		result += strings[i];
		result += "<b>" + highlights[i] + "</b>";
	}
	result += strings[strings.length - 1];
	return result;
}

let name = "John Doe";
let age = 42;

let s = Highlight`${name} is ${age} years old`;
alert(s);

Pay special attention to the two parameters of the Highlight() function. The first one, called literals, will be an array of all parts of the passed in string that are NOT placeholder values. For the second parameter, called highlights, we use the spread syntax to get an array of the placeholder values passed to the string (in this case, name and age). I then use these two arrays to re-construct the string while adding HTML tags around the placeholder values.

As mentioned already, tagged templates are pretty much only used to solve complex templating tasks, but I wanted to give you quick glimpse of how it works anyway, for completeness.

Summary

This article was all about learning how to define a string and the multiple ways of doing that in JavaScript. The next step is to learn how to work with them and manipulate them, and luckily for us, JavaScript comes with the built-in String object, offering us a LOT of functionality for doing just that.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!