Better Strings (Template Strings)


A string is a string is a string, right?

Well, yes. But beyond "hello, world!" we normally need to do a little more with our strings.

Even so, let's start with the basics.

We have the double quoted PHP variant:

echo "hello, world!";

And there's also the single quotes equivalent:

echo 'hello, world!';

What's the difference? Not very much, if we have just a basic string.

Technically it's marginally (and we are talking the minutest of margins) more performant to use the single quoted variant for plain strings, as double quoted strings have one extra feature, as we shall see momentarily.

There are two other types of PHP string: heredoc and nowdoc syntax. These are less frequently used (by me, at least) and are not covered here. You can read more about both on the official PHP docs.

In JavaScript, whether in ES5 or ES6 and beyond, a string has no special differences between the single and double quoted equivalent:

console.log("this is a string");
console.log('and so is this');

Added in JavaScript's ES6, we now also have template strings.

Template strings use back quotes (`):

// ES6 only
console.log(`a template string`);

Template strings are really quite nice, and add some useful functionality as we shall soon see.

Introducing Variables

As mentioned, when all we have is a plain old string (e.g. our "hello, world!" text), whichever string variant we choose is probably good enough.

More often than not, however, we need to include some variables or bits of dynamically created data into our strings.

Of course, both PHP and JavaScript have you covered here. But that doesn't mean the syntax is always that pretty.

With PHP, when using double quoted strings we can include variables right inside our strings:

$name = 'Chris'
echo "hello, $name!";

// outputs "hello, Chris!"

The syntax looks a little strange here though. Is the exclamation mark part of the variable name, or not?

Well, we know it's not because an exclamation mark is not a valid character for use in the name of a variable.

But if you were a complete beginner, this might not be super obvious.

Incidentally it's because strings with double quotes can contain variables that they are slightly less efficient than their single quoted cousins.

Anyway, to remove any potential confusion, we can use curly braces {} around any variable name to indicate that this is indeed a variable:

$name = 'Chris'
echo "hello, {$name}!";

// outputs "hello, Chris!"

For clarity, when using single quotes we cannot expand variables simply by including them:

$name = 'Chris'

echo 'hello, $name!';

// outputs "hello, $name!"

echo 'hello, {$name}!';

// outputs "hello, {$name}!"

PHP offers some alternative approaches here.

We can use the period (.) to concatenate variables and string literals together:

$name = 'Chris'
echo 'hello, ' . $name . '!';

// outputs "hello, Chris!"

Or we could use sprintf to create a nicely formatted string:

$name = 'Chris'
echo sprintf('hello, %s!', $name);

// outputs "hello, Chris!"

sprintf is one of my favourite functions in PHP. There's plenty it can do and if you find yourself using 'string' . ' ' . 'concatenation' then consider sprintf as a likely much nicer, neater alternative.

sprintf for JavaScript?

Unfortunately, JavaScript doesn't have a native sprintf function.

We can still concatenate strings, only instead of using the period (.) like in PHP, we need to use the plus sign (+) instead. To me, this seems even weirder than using the period, as it reads like adding strings together. But whatever, it works:

var name = 'world';

console.log("hello, " + name + "!");
// outputs "hello, world!"

console.log('goodbye, ' + name + '!');
// outputs "goodbye, world!"

Without using a third party library, this is about as good as it gets in ES5 era JavaScript.

However, as mentioned above, ES6 comes with Template literals. These things are super useful.

By wrapping our strings in back ticks we gain functionality somewhat similar to sprintf, but more besides:

const name = 'Chris';
console.log(`hello, ${name}!`);

// outputs "hello, Chris!"

We don't need to stop with simple variables here either. We can pass in more complex expressions, a trivial example being:

console.log(`2 + 2 = ${2 + 2}!`);

// outputs "2 + 2 = 4!"

console.log(`3 * 3 = ${true && 3 * 3}!`);

// outputs "3 * 3 = 9!"

This is cool. It's also very useful.

Template strings can also be multi-line without needing to use the new line character and string concatenation:

console.log('this is the first line \n' +
' and this is the second');

// outputs:
// "this is the first line
//  and this is the second"

console.log(`I can
span multiple lines,
no problem`);

// outputs:
// I can
// span multiple lines,
// no problem

You can even call functions from your Template literals:

const whoShouldICall = () => 'Ghost Busters';

console.log(`who ya' gunna call? ${ whoShouldICall() }!`);

// outputs:
// who ya' gunna call? Ghost Busters!

Kinda nice.

Template literals are the gentlest introduction to ES6 in my opinion. They are almost immediately useful in any project.

Episodes

# Title Duration
1 Better Strings (Template Strings) 04:00