Quick actions

cmd+k|ctrl+k

Navigation

Languages

String Reversal using Recursion and Iteration

Snippet info

Language

JavaScript

Visibility

public

Author

dhamankovachi1

Created

2023-12-04T14:09:30.80149Z

Updated

2023-12-04T14:09:30.80149Z

function reverseString(str) {
  let arrayStr = str.split("");
  let reversedArray = [];
  //We are using closure here so that we don't add the above variables to the global scope.
  function addToArray(array) {
    
    if(array.length > 0) {
      reversedArray.push(array.pop());
      addToArray(array);
    }
    return;
  }
  addToArray(arrayStr);
  return reversedArray.join("");
}

reverseString('yoyo master');

function reverseStringRecursive (str) {
  if (str === "") {
    return "";
  } else {
    return reverseStringRecursive(str.substr(1)) + str.charAt(0);
  }
}

reverseStringRecursive('yoyo master');
INFO