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 92 times
0
Joseph
- 5,548
- 14
- 57
- 125
-
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
3
[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
- 123,782
- 12
- 99
- 138
0
You can nest and use a ternary
const firstName = "John"
const lastName="Doe"
console.log(
`${firstName} ${typeof middleName !== "undefined" ? `${middleName} ` : ''}${lastName}`
)
mplungjan
- 155,085
- 27
- 166
- 222
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
- 266
- 3
- 12
-
-
-
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
- 8,973
- 3
- 23
- 37
-
That is not what was asked. Try commenting out your `// const middleName="middle";` – mplungjan Apr 29 '21 at 08:30