Overview
Combining multiple strings and variables into one is a fundamental task in programming, whether you are concatenating user inputs or constructing API request URLs. This article explains how to implement string concatenation using “Template Literals,” a feature introduced in ES6 that offers superior readability and maintainability compared to the traditional + operator.
Specifications (Input/Output)
- Input: Two text fields for “Department Name” and “Full Name.”
- Output: A formatted “Display Name” generated in real-time by joining the two inputs.
- Operation: * Execute concatenation every time the user enters text.
- If a department name is provided, wrap it in square brackets
[]for emphasis.
- If a department name is provided, wrap it in square brackets
Basic Usage
There are two primary ways to concatenate strings in JavaScript. Currently, Template Literals using backticks (`) are recommended.
const greet = "Hello";
const target = "World";
// 1. Template Literals (Recommended)
// You can embed variables using ${} and write multi-line strings directly.
const modern = `${greet} ${target}`;
// 2. Plus Operator (Traditional)
// Managing quotes can become complex when there are many concatenation points.
const classic = greet + " " + target;
Full Code Examples
HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Concatenation Demo</title>
<style>
body { font-family: sans-serif; padding: 20px; max-width: 600px; }
.input-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input { padding: 8px; width: 100%; box-sizing: border-box; }
.preview-box {
background-color: #e3f2fd;
padding: 15px;
border-left: 5px solid #2196f3;
border-radius: 4px;
margin-top: 20px;
}
.preview-label { font-size: 0.8em; color: #555; margin-bottom: 5px; }
.preview-text { font-size: 1.2em; font-weight: bold; min-height: 1.2em; }
</style>
</head>
<body>
<h2>ID Card Display Name Preview</h2>
<div class="input-group">
<label for="deptInput">Department</label>
<input type="text" id="deptInput" placeholder="e.g., Engineering">
</div>
<div class="input-group">
<label for="nameInput">Full Name</label>
<input type="text" id="nameInput" placeholder="e.g., Taro Tanaka">
</div>
<div class="preview-box">
<div class="preview-label">Generated Display Name:</div>
<div id="displayName" class="preview-text"></div>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
/**
* Get references to HTML elements
*/
const deptInput = document.getElementById("deptInput");
const nameInput = document.getElementById("nameInput");
const displayName = document.getElementById("displayName");
/**
* Function to join input values and update the preview
*/
const updatePreview = () => {
// Get form values and trim whitespace
const dept = deptInput.value.trim();
const name = nameInput.value.trim();
// Join strings using Template Literals
// Conditional logic to wrap the department in [] and add a space if it exists
// Use a ternary operator to control the embedded value
const formattedDept = dept ? `[${dept}] ` : "";
// Create the final concatenated string
// Example: "[Engineering] Taro Tanaka"
const fullName = `${formattedDept}${name}`;
// Render the result
displayName.textContent = fullName;
};
// Use the 'input' event for real-time updates
deptInput.addEventListener("input", updatePreview);
nameInput.addEventListener("input", updatePreview);
Customization Tips
- Numeric Calculations: You can write expressions inside
${}within a template literal. For example,Total: ${price * 1.1}allows you to perform calculations and concatenation simultaneously. - Handling Newlines: Template literals preserve newlines exactly as written in the source code. This is very useful for creating long messages or HTML templates stored as strings.
Important Notes
- Concatenating Numbers and Strings: When using the
+operator, adding a number and a string results in string concatenation (e.g.,10 + "20" === "1020"). To avoid type-conversion bugs, clearly distinguish between math and concatenation, or use template literals consistently. - Displaying undefined / null: If you concatenate variables that are
undefinedornull, they will be displayed as the literal strings “undefined” or “null.” It is important to use methods liketrim()or ternary operators to implement empty-string fallbacks as shown in the code example.
Advanced Applications
Joining Array Elements (join)
If you want to join multiple strings stored in an array using a specific delimiter, use the join() method. This is helpful for generating tag lists or CSV data.
const tags = ["JavaScript", "HTML", "CSS"];
// Join with a comma and a space
const tagList = tags.join(", ");
console.log(tagList); // "JavaScript, HTML, CSS"
Conclusion
Template literals (using backticks) are the modern standard for string concatenation due to their high readability and low potential for errors. They are especially powerful when embedding variables or handling text with newlines. However, always ensure robust implementation by validating and normalizing input values to prevent unexpected strings like “undefined” from appearing in your UI.
