How to reverse a string in JavaScript using a "for...in" loop?

Solution 1:

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);

Solution 2:

Even using the arrow function you could reverse a string.

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

Solution 3:

No need to use for in

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