Avoid Unexpected string concatenation in JavaScript?

JavaScript string concatenation can lead to unexpected results when mixing strings and numbers. Using template literals with backticks provides a cleaner, more predictable approach than traditional concatenation methods.

The Problem with Traditional Concatenation

When using the + operator, JavaScript may perform string concatenation instead of numeric addition:

let name = "John";
let age = 25;
let score = 10;

// Unexpected string concatenation
console.log("Age: " + age + score);  // "Age: 2510" (not 35!)
console.log(name + " is " + age + " years old");
Age: 2510
John is 25 years old

Using Template Literals (Recommended)

Template literals with backticks (`) and ${} syntax provide cleaner string interpolation:

const concatValue = 'John,David,Mike';
let friendNames = `${concatValue}`;
let studentNameWithFriends = `${concatValue} | 'Carol' | 24`;

console.log(friendNames);
console.log(studentNameWithFriends);
John,David,Mike
John,David,Mike | 'Carol' | 24

Complex Example with Multiple Data Types

let studentName = "Alice";
let age = 22;
let grade = 'A';
let friends = ["Bob", "Carol", "Dave"];

// Clean template literal approach
let result = `Student: ${studentName}, Age: ${age}, Grade: ${grade}, Friends: ${friends.join(', ')}`;
console.log(result);

// Avoid this messy concatenation
let messyResult = "Student: " + studentName + ", Age: " + age + ", Grade: " + grade;
console.log(messyResult);
Student: Alice, Age: 22, Grade: A, Friends: Bob, Carol, Dave
Student: Alice, Age: 22, Grade: A

Comparison

Method Readability Type Safety Multiline Support
+ operator Poor Risky No
Template literals Excellent Safe Yes

Conclusion

Template literals with backticks provide safer, more readable string concatenation. They eliminate unexpected type coercion and make code more maintainable than traditional + concatenation.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements