Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
