Constructing a sentence based on array of words and punctuations using JavaScript


We are required to write a JavaScript function that takes in an array of words and punctuations. Our function should join array elements to construct a sentence based on the following rules −

  • there must always be a space between words;

  • there must not be a space between a comma and word on the left;

  • there must always be one and only one period at the end of a sentence.


Following is the code −

 Live Demo

const arr = ['hey', ',', 'and', ',', 'you'];
const buildSentence = (arr = []) => {
   let res = '';
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const next = arr[i + 1];
      if(next === ','){
         res += el;
            res += `${el}.`;
            res += `${el} `;
   return res;


hey, and, you.