How do you combine firstName, middleName and lastName in ES6?
What I do is ${firstName} ${middleName} ${lastName}
But the problem there is a space in between if middleName is not there. Middle name is not always present
Asked
Active
Viewed 297 times
0

Joseph
- 7,042
- 23
- 83
- 181
-
2Tip: Ternary operator. Or forget templates and `[ ... ].filter(...).join(' ')` – tadman Apr 29 '21 at 08:12
-
`[firstName, middleName, lastName].filter(x => x).join(' ')` – msbit Apr 29 '21 at 08:14
4 Answers
4
[firstName, middleName, lastName].filter(Boolean).join(" ")
should work just fine.
Since the empty string is falsy and Boolean(x)
will compute the truthiness of x
, .filter(Boolean)
will drop it.

AKX
- 152,115
- 15
- 115
- 172
0
You can nest and use a ternary
const firstName = "John"
const lastName="Doe"
console.log(
`${firstName} ${typeof middleName !== "undefined" ? `${middleName} ` : ''}${lastName}`
)

mplungjan
- 169,008
- 28
- 173
- 236
0
You can remove the first space between the first and middle name and handle it in the middle name itself example:
`${firstName}${middleName ? ' ' + middleName : ''} ${lastName}`

Ali Ataf
- 391
- 3
- 13
-
-
-
Yes, I am assuming that middleName is always defined but may not have a value – Ali Ataf Apr 29 '21 at 08:24
0
You can do so by using javascript template literals:
const firstName = "John";
const lastName="Doe";
const middleName="middle";
const printFullName = (firstName, lastName, middleName) => {
console.log(
`${firstName}${middleName ? ` ${middleName}` : ''} ${lastName}`
)
}
printFullName(firstName, lastName);
printFullName(firstName, lastName, middleName);

Ran Turner
- 14,906
- 5
- 47
- 53
-
That is not what was asked. Try commenting out your `// const middleName="middle";` – mplungjan Apr 29 '21 at 08:30