How to make js built-in function

khaled-17 - Jul 29 - - Dev Community

We will explain a function to which we send the array and convert all its contents to lowercase letters

 const toLowerCaseArray = (array) => {
  if (!Array.isArray(array)) {
    throw new Error('Input must be an array');
  }

  return array.map(item => {
    if (typeof item === 'string') {
      return item.toLowerCase();
    }
    return item; // Return the item unchanged if it's not a string
  });
};

 var array1 = ['Hello', 'WORLD', 'JavaScript'];

 var lowerCaseArray1 = toLowerCaseArray(array1);

 console.log(lowerCaseArray1);

Enter fullscreen mode Exit fullscreen mode

Yes, as you can see, it is just a function. Send in the array parameter. Then the function converts all its elements into to Lower Case for words.

But we hope we don't build something much stronger

Image description

*We want to build something that uses JavaScript connectivity
*

var array1 = ['Hello', 'WORLD', 'JavaScript'];

 var lowerCaseArray1 = array1.toLowerCaseArray();

 console.log(lowerCaseArray1);
Enter fullscreen mode Exit fullscreen mode

NOT

 var array1 = ['Hello', 'WORLD', 'JavaScript'];

 var lowerCaseArray1 = toLowerCaseArray(array1);

 console.log(lowerCaseArray1);
Enter fullscreen mode Exit fullscreen mode

Image description

Our code will be

 Array.prototype.toLowerCaseArray = function() {
  if (!this.every(item => typeof item === 'string')) {
    throw new Error('All elements in the array must be strings');
  }

  return this.map(item => item.toLowerCase());
};

 var array1 = ['Hello', 'WORLD', 'JavaScript'];

 var lowerCaseArray1 = array1.toLowerCaseArray();

 console.log(lowerCaseArray1);

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player