Theme

Template String

The first section we will learn about syntactic sugar in modern JavaScript.

Syntactic Sugar is a term to describe a syntax that is introduced in a programming language to make things easier to read or to express without adding new features. In other words, all the syntatical sugar can be translated to older syntax.

Therefore, for this section, I will show you the code written with old JavaScript, and then show you the code written with the new syntax.

The first syntactic sugar that we will learn is template string.

Template String

With old JavaScript, to generate a string that consists of variables, you need to use string concatenation.

var firstName = 'Malcolm';
var lastName = 'Kee';

var greeting = 'Hi! My name is ' + firstName + ' ' + lastName + '.';

console.log(greeting);

With template string:

var firstName = 'Malcolm';
var lastName = 'Kee';

var greeting = `Hi! My name is ${firstName} ${lastName}.`;

console.log(greeting);

Another good things about template string is that it can handle multiple lines.

var firstName = 'Malcolm';
var lastName = 'Kee';

var greeting = `Hi! 
My name is
${firstName} ${lastName}.`;

console.log(greeting);

Exercise

Refactor the following code to use template string.

function greet(firstName, lastName, salutation) {
  console.log('Hi ' + salutation + ' ' + firstName + ' ' + lastName + ', welcome!');
}

greet('Malcolm', 'Kee', 'Mr.');