Avoid Unexpected string concatenation in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.

We have the following −

const concatValue = 'John,David,Mike';
var friendNames= `${concatValue}`;

The above value is concatenated with a string and number −

var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;

Following is the complete JavaScript code for concatenation −

Example

const concatValue = 'John,David,Mike';
var friendNames= `${concatValue}`;
var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;
console.log(friendNames);
console.log(studentNameWithFriends);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo37.js

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo37.js
John,David,Mike
John,David,Mike| 'Carol' | 24
raja
Published on 01-Sep-2020 11:35:10
Advertisements