Home » String Interpolation in JavaScript

String Interpolation in JavaScript

In this tutorial let’s learn about String Interpolation in JavaScript.

Contents

JavaScript String Interpolation

String interpolation is a wonderful programming language feature that allows you to easily inject variables, function calls, and arithmetic expressions into a string. String interpolation was not available in JavaScript prior to ES6. String interpolation is a new feature in ES6 that allows you to create multi-line strings without using an escape character. We can easily utilize apostrophes and quotes to make our strings and, as a result, our code easier to read.

String Interpolation vs String Concatenation

These are a few of the advantages of string interpolation versus string concatenation.

String Concatenation code:

const info = (name, topic) => { 
    return "Website " + name + " tutorial: " + topic ;  
} 
console.log(info("SimilarGeeks", "JavaScript")); 

Output :

Website SimilarGeeks tutorial: JavaScript

String interpolation is a feature that allows you to directly inject variables, function calls, and arithmetic expressions into a string without utilising concatenation or an escape character for multi-line strings.

In string interpolation, we utilise backticks for template literals and the syntax – $ourValue to insert dynamic values like as variables, function calls, and arithmetic expressions.

String interpolation Code:

const info = (name, topic) => { 
    return `Website   ${name}  tutorial: ${topic} `;  
} 
console.log(info("SimilarGeeks", "JavaScript")); 

Output :

Website   SimilarGeeks  tutorial: JavaScript

We can perform many operations like below example it states whether the given number is even or odd.

Code Example :

const cal = (num) => { 
    console.log(`Number is ${num%2 === 0 ? 'even' : 'odd'}`); 
} 
cal(3);
cal(6);

Output :

Number is odd
Number is even

Conclusion

String Interpolation in JavaScript is introduced in the recent versions but has many advantages over string concatenation. String interpolation is an excellent feature that allows you to inject values into string literals in a succinct and legible manner. Also, avoid the clunky string concatenation method.

Similar Posts:

How to Check if a String is Empty in JavaScript
Remove the First Character From String in JavaScript