
How to Add a Variable Inside a String in JavaScript?
Do you want to know how to add a variable inside a string in JavaScript? If so, then this blog post is for you! It's actually quite simple and can be done with just one line of code. All you need is the plus operator (+).
How to Concatenate Two Variables Using String Concatenation#
One of the simplest ways to add a variable inside a string in JavaScript is by using string concatenation.
This method involves combining multiple strings and variables together using the concatenation operator (+).
Let's say we have two variables: name and age. To insert them into our string, all we need to do is use the + operator like this:
The output will be My name is John, I am 30. Easy right? You can also combine multiple strings together by adding them with the + sign as well. For example:
<script> console.log("Hello there," + "my name is " + name); </script>
Concatenate Two Variables Using Template Literals#
Template literals, introduced in ECMAScript 2015 (ES6), provide a more convenient and readable way to include variables inside strings.
To concatenate two variables in JavaScript using template literals, you can use the ${} syntax to interpolate the variables inside backticks.
In the above example, the template literal is enclosed in backticks and the variables firstName and lastName are enclosed within ${}.
When the code is executed, the variables are interpolated inside the template literal and the output is Apu Gorai.
You can also perform operations inside the ${} syntax, such as simple arithmetic and function calls. For example: