Literal string with a variable inserted

Literal string with a variable inserted

When working with strings in programming, it is common to have a need to insert variables into a string. One way to do this is by using a literal string with a variable inserted. In this method, we create a string that contains a placeholder for the variable, and then we use a method to replace that placeholder with the actual variable value.


const name = "Raju";
const message = `Hello ${name}, welcome to my blog!`;

In the above example, we have created a string using backticks (`) which allows us to insert variables using ${variable}. In this case, we have inserted the value of the name variable into the string. When we log the message variable to the console, it will output "Hello Raju, welcome to my blog!".

Another way:

Another way to do this is by using the concatenation operator (+) to concatenate strings and variables together. It looks like this:

const name = "Raju";
const message = "Hello " + name + ", welcome to my blog!";

This will output the same result as the previous example.


Both methods work well and it's up to personal preference which one to use. However, using literal strings with variables inserted is becoming more popular as it is easier to read and can make the code more concise.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]