[JavaScript – ES2015] Literals and Templates

ES2015 has two new numeric literals (binary and octal). Also let’s see what template literals do.

 

1. Binary and Octal Literals

The hexadecimal literals (0x) have been around but binary (0b) and octal (0o) literals are new addition.

console.log(10);
console.log(0b1010);
console.log(0o12);
console.log(0xa);

They are all 10.

 

2. Template Literals

Template literals or Template strings provide the easy syntax to construct strings. It is similar to C#’s string interpolation ($”…{…}..”). In JavaScript, the backtick (`) character is used to define the template and the “${…}” is used for a placeholder.

The template literals are very useful to concatenate strings.

let protocol = "http";
let host = "mysite.com";
let page = "about";
let url1 = protocol + "://" + host + "/" + page;
console.log(url1);
let url2 = `${protocol}://${host}/${page}`;
console.log(url2);

To escape the backtick or $ character, you can use the backslash ‘\’.

let price = 9.9;
console.log(`\`price\` = \$${price}`); // `price` = $9.9

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s