10
525

How to perform string Interpolation in JavaScript in ES6

Reading Time: 2 minutes

String interpolation in ES6 have make coding a much more easier operation and readable compare to how we want to do it in the past.

What exactly is it?

Wiki have a very detailed explanation. To simplify it, string interpolation is to replace the variables within a string to replace with the values you want after it finish processing.

String Interpolation in ES5

During the times before ES6 started, it is common to join the strings with variables by breaking up the sentence into pieces and join them up with + operator.

Below shows an example of the codes in ES5.

var appleCount = 5;

console.log("I have " + appleCount + " apple(s).");

String Interpolation in ES6

With the release of ES6 or ECMAScript 2015, this has become something more constructive and more functional. Let’s look at the below example below we goes into the details to example.

const appleCount = 5;

console.log(`I have ${appleCount} apple(s).`);

Have you already notice some of the changes?

The whole sentence stays together with the use of backticks ` and the variable is now surrounded by a “${}” placeholder for the code to understand that whatever inside needs to be processed.

Le’s look into other more complex examples.

const appleCount = 5;
const orangeCount = 10;

let sentence1 = `I have ${appleCount} apple(s) and ${orangeCount} orange(s).`
// I have 5 apple(s) and 10 orange(s).

let sentence2 = `I have ${appleCount + orangeCount} fruit(s).`
// I have 15 fruit(s).

let sentence3 = `I have \${appleCount} fruit(s).`
// I have ${appleCount} fruit(s).

From the above examples, we can observed a few things. String interpolation allows multiple variables place inside a string and it will also allow you to add any expression inside the braces where it will process it before getting displayed. It also still allow the code to display as it is by placing a backslash before ‘$’ character.

Conclusion

With string interpolation is widely applicable into our everyday code. Now that ES6 have improve it to allow a more readable and structured manner, it has really help developers to write more readable codes!

Show Comments

No Responses Yet

Leave a Reply