Construct Full Name from First, Last 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 −

 Live Demo

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
Updated on: 2021-04-20T07:39:03+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements