HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Reverse string in JavaScript without using reverse()

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutreversejavascriptusingstring

Problem

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 > -1; i--) {
    result.push(newarr[i]);
  }
  str = result.join("");
  return str;
}

reverseString("hello");

Solution

-
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 "middle" 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

Context

StackExchange Code Review Q#133769, answer score: 9

Revisions (0)

No revisions yet.