Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptString Interpolation in JavaScript

String Interpolation in JavaScript

String interpolation is a great programming language feature that allows injecting variables, function calls, arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6. String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well. These are some of the reasons to use string interpolation over string concatenation.

Let’s see the difference between string concatenation and string interpolation.




<script>
  
// String Concatenation
function myInfo(fname, lname, country) {
    return "My name is " + fname + " " + lname + ". " 
              + country + " is my favorite country."
}
console.log(myInfo("john", "doe", "India"));
</script>


Output:

My name is john doe. India is my favorite country

In string concatenation, it is hard to maintain string as they grow large it becomes tedious and complex. In order to make it readable, the developer has to maintain all the whitespaces. This is where ES6 comes to rescue with String interpolation. In JavaScript, the template literals (strings wrapped in backticks ` `) and ${expression} as placeholders perform the string interpolation. Now we can write above myInfo function with string interpolation.




<script>
  
// String Interpolation
function myInfo(fname, lname, country) {
    return `My name is ${fname} ${lname}. ${country} is my favorite country`; 
}
console.log(myInfo("john", "doe", "India"));
</script>


Output:

My name is john doe. India is my favorite country

We can see that the code is small and easily readable as compared to concatenation. The template string supports placeholders. The expression like variables, function call, arithmetic can be placed inside the placeholder. These expressions are evaluated at runtime and output is inserted in the string.




<script>
  
// DEclare and initialize variables
const x = "neveropen";
  
// I like neveropen
console.log(`I like ${x}.`);
  
// Function call
function greet() {
    return "hello!";
}
  
// hello! I am a student.
console.log(`${greet()} I am a student.`); 
  
// Expression evolution
//sum of 5 and 6 is 11. 
console.log(`sum of 5 and 6 is ${5+6}.`);
  
</script>


Output:

I like neveropen
hello! I am a student.
sum of 5 and 6 is 11.

We can also use conditional statements in expression. For example:




<script>
  
function isEven(x) {
    console.log(`x is ${x%2 === 0 ? 'even' : 'odd'}`);
}
  
isEven(4); // x is even
</script>


Output:

x is even

The string interpolation is a great feature. It helps in inserting values into string literals. It makes code more readable and avoids clumsiness.

RELATED ARTICLES

Most Popular

Recent Comments