Avoid Unexpected string concatenation in JavaScript?


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

Updated on: 01-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements