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


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.


Following is the code −

 Live Demo

const firstName = 'Vijay';
const lastName = 'Raj';
const constructName = (firstName, lastName, middleName) => {
      middleName = '';
   let nameArray = [firstName, middleName, lastName];
   nameArray = nameArray.filter(Boolean);
   return nameArray.join(' ');
console.log(constructName(firstName, lastName));


Following is the console output −

Vijay Raj