Reverse string in JavaScript without using reverse() I have to reverse a string in JavaScript and cannot use the built in reverse() function. It does not seem efficient to have to create two arrays but is there a better way?

function reverseString(str) {
  newarr = str.split("");
  result = [];
  x = newarr.length;
  for (i = x; i &gt; -1; i--) {
    result.push(newarr[i]);
  }
  str = result.join("");
  return str;
}

reverseString("hello");
One array to rule them all
You do not need to create two arrays; one is enough. Simply swap slots until you've reached the &quot;middle&quot; of the array.

Declare your variables
It is better to use the var keyword to define your variables. Otherwise, they are declared on the top-level scope, i.e; they become global, and may be accessed and modified by other functions.

Why not use reverse()?
You do not say why you cannot use built-in functions. If you happen to have some base code which overrides native functions, then some groaning and roaring is in order.




function reverse(str) {
  var chars = str.split("");
  var length = chars.length;
  var half = length / 2;
  for (var ii = 0; ii &lt; half; ii++) {
    var temp = chars[ii];
    var mirror = length - ii - 1;
    chars[ii] = chars[mirror];
    chars[mirror] = temp;
  }
  return chars.join("");
}

console.log(reverse("abcd"));
console.log(reverse("abcde"));