Swapcase function in JavaScript

We are required to write a JavaScript function that takes in a string as the only argument.

The string might contain both uppercase and lowercase alphabets.

The function should construct a new string based on the input string in which all the uppercase letters are converted to lowercase and all the lowercase letters are converted to uppercase.


Following is the code −

const str = 'ThIs Is A STriNG';
const findLetter = (char = '') => {
   if(char.toLowerCase() === char.toUpperCase){
      return char;
   }else if(char.toLowerCase() === char){
      return char.toUpperCase();
      return char.toLowerCase();
const swapCase = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      res += findLetter(el);
   return res;


Following is the output on console −

tHiS iS a stRIng