Enhanced string concatenation/interpolation in ES6
August 6, 2017 Leave a comment
ES6 comes with a new syntactic feature that makes concatenating strings easier. Here’s an example of creating an object with a function with traditional string concatenation in JavaScript:
function person(name, age, country, language) { return { name, age, country, language, introduceMe() { return 'My name is ' + this.name + ', I am ' + this.age + ' years old, I am from ' + this.country + ' and I speak ' + this.language + '.' } } }
Here’s an example of usage:
let p = person('Ivica', 20, 'Croatia', 'Croatian') p.introduceMe()
introduceMe in the above example returns the following:
My name is Ivica, I am 20 years old, I am from Croatia and I speak Croatian.
In ES6 we can use the $ operator and enclose those property calls within curly braces to build the string. Here’s the revised introduceMe() function. Also, the whole string must be surrounded by backticks which can be difficult to find on your keyboard. A backtick looks like this: `
function person(name, age, country, language) { return { name, age, country, language, introduceMe() { return `My name is ${this.name}, I am ${this.age} years old, I am from ${this.country} and I speak ${this.language}.` } } }
I think the biggest benefit is not actually writing fewer characters. I like the way how we don’t need to open and close the quotation marks and join the various bits with the + sign. Finding and typing the backtick character will take a bit of time to get used to though.
View all posts related to JavaScript here.