Enhanced string concatenation/interpolation in ES6

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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 )

Facebook photo

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

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: