-5

I have a piece of JavaScript code using a for loop to reverse a string. However, I would like to know if it is possible to use a for in loop instead and how would I go about that?

     function reverse(str){
         var reversedString = '';
         for (var i = str.length - 1; i >= 0; i--){
            reversedString = reversedString + str[i];
     }
     return reversedString;
   }

   alert(reverse('hello'));
2
  • 4
    Do not use for...in on a string it will iterate over properties that are not numeric indexes Commented Jan 4, 2018 at 9:05
  • 2
    for in is for looping over enumerable properties. It isn’t even guaranteed by the spec to iterate in order, though in practice it does. There is no correct way to accomplish this task with for in. Commented Jan 4, 2018 at 9:17

7 Answers 7

6

From MDN Docs

for...in should not be used to iterate over an Array where the index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

let iterable = '1234567';
String.prototype.hello = "hello";  // doesn't affect
let reversed = "";
for (let value of iterable) {
  reversed = value + reversed;
}

console.log(reversed);

Feature        Chrome   Edge    Firefox Internet Explorer   Opera   Safari
Basic support   38       12       131       No                25        8

Break for..in (see the hello creeping in)

let iterable = '1234567';
String.prototype.hello = "hello";
let reversed = "";
for (let index in iterable) {
  reversed = iterable[index] + reversed;
}

console.log(reversed);

Sign up to request clarification or add additional context in comments.

1 Comment

This because indeed the "index" value start value in the for in loop is 4(hello.length)
3

Even using the arrow function you could reverse a string.

 const reverseString = (str) => str.split("").reverse().join("");
 console.log(reverseString("hello"))

Comments

2

You shouldn't use for...in in this case. for...in was designed for iterating through object literals, not for strings or arrays.

[...'mystring'].reverse().join('')
Array.from('mystring').reverse().join('')

I recommend you to use spread syntax or Array.from to convert strings into arrays instead of .split('') since split('') won't work in the case of multibytes unicode characters.

console.log([...'\uD83D\uDE80']);
console.log('\uD83D\uDE80'.split(''));

1 Comment

Nice answer, better than all other copy pasted ones.
1

No need to use for in

'mystring'.split('').reverse().join('')

3 Comments

Nice answer, but I still think "if it ain't broke, don't fix it". You could also argue that the OPs current method is more readable.
I think that OP knows this solution with built-in reverse function, but he needs his own reverse() function. Actually, OP already got it, but want some improvements. :)
This doesn't answer the question
1

You can used split() & reduce() functions

let str = "hello";
return  str.split('').reduce((rev,char) =>
   char + rev,
'');

Comments

1

Reverse string using while loop

    function reverseStr(word) {
      let reversed = '';
      let i = 0;
      while (i < word.length) {
        reversed = word[i] + reversed;
      i++;
        }
      return reversed;
     }
    
    

Comments

0

function reverse(str) {
  let reversed = "";
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

console.log("stefana")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.