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
Constructing full name from first name, last name and optional middle name in JavaScript
We need to write a JavaScript function that takes in three strings: first name, last name, and an optional middle name, then returns the full name constructed from these inputs.
Problem
The challenge is handling the optional middle name parameter. If no middle name is provided, we should construct the full name with just the first and last names, avoiding extra spaces.
Using Array Filter Method
This approach uses an array to collect all name parts, filters out empty values, and joins them with spaces:
const firstName = 'Vijay';
const lastName = 'Raj';
const constructName = (firstName, lastName, middleName) => {
if (!middleName) {
middleName = '';
}
let nameArray = [firstName, middleName, lastName];
nameArray = nameArray.filter(Boolean);
return nameArray.join(' ');
};
console.log(constructName(firstName, lastName));
console.log(constructName('John', 'Doe', 'Michael'));
Vijay Raj John Michael Doe
Using Conditional String Concatenation
A simpler approach using conditional logic to build the name string:
const constructNameSimple = (firstName, lastName, middleName) => {
if (middleName) {
return `${firstName} ${middleName} ${lastName}`;
}
return `${firstName} ${lastName}`;
};
console.log(constructNameSimple('Alice', 'Smith'));
console.log(constructNameSimple('Alice', 'Smith', 'Jane'));
Alice Smith Alice Jane Smith
Using Default Parameters
Modern JavaScript approach using default parameters and array methods:
const constructNameModern = (firstName, lastName, middleName = '') => {
return [firstName, middleName, lastName]
.filter(name => name.trim())
.join(' ');
};
console.log(constructNameModern('David', 'Wilson'));
console.log(constructNameModern('David', 'Wilson', 'Paul'));
console.log(constructNameModern('Sarah', 'Johnson', ''));
David Wilson David Paul Wilson Sarah Johnson
Comparison
| Method | Readability | Performance | Modern Syntax |
|---|---|---|---|
| Array Filter | Good | Medium | Yes |
| Conditional | Excellent | Best | Yes |
| Default Parameters | Good | Medium | Yes |
Conclusion
The conditional string concatenation method offers the best balance of readability and performance. Use array methods when you need to handle more complex name formatting scenarios.
