Computer >> Computer tutorials >  >> Programming >> Javascript

Constructing full name from first name, last name and optional middle name in JavaScript


Problem

We are required to write a JavaScript function that takes in three strings, first string specifies the first name, second string specifies the last name and the third optional string specifies the middle name.

Our function should return the full name based on these inputs.

Example

Following is the code −

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));

Output

Following is the console output −

Vijay Raj