1

I want to reverse a string without build in function such split, reverse and join, i have try the code from here https://stackoverflow.com/a/51751393/8070090 , but i am not realy understand what's the code do on the fourth line, i need more explanations on the fourth line. This is my code with some explanation

 function reverseString(str) {
  reverseIt = [];
  for (i = 0; i < str.length; i++) {
    reverseIt = str[i] + reverseIt; // the first way that works
    // reverseIt = str[i] + [];    // first.. i assume the variable "reverseIt" is equal to "[]", but the result from this line is not equal to the line above
    // reverseIt = str[i] + '';    // then i try this way with assume the variable reverseIt is empty string (""), but the result from this line not produce the expected result

    // var testing = [];             // and then  i try to make an empty array variable again
    // reverseIt = str[i] + testing; // and try to add the variable above, but this still not realy produce the expected result
    /*
      So the questions.., why the first way can works..?, what's actualy the code on that line do..?
    */
  }
  return reverseIt;
}
console.log(reverseString('Javascript'));
Tri
  • 2,722
  • 5
  • 36
  • 65

4 Answers4

3

Literally it says that start from the first character to the end, and at each step, add the new character before the whole created string

So for example for the name david, it starts from an empty string, then pushes every letter to the beginning of the series. starting from nothing, then d, then adds a to the beginning, which would make ad, then add v to become vad, and so on to end in divad

-> What you tried with this code:

reverseIt = str[i] + [];

is not the same as the original code. Because reverseIt is [] only at the beginning! (Just note that this [] is equal to '' here, because the string is just an array of string in that matter! so this contains both cases.)

It is [] (or '', no difference here) at first indeed, but procedeeing one level, it becomes d! then the new str[i] is a which then concatenates to reverseIt which is now d, and then the result becomes ad that will be put in reverseIt! so at the end of this step, the reverseIt variable is equal to ad, not []! and it continues like this until the whole string is reversed.

-> What you tried with this code:

var testing = [];
reverseIt = str[i] + testing;

is not correct, because you are literally reseting your reversed string at each step and you are not concatenating the new string to the already created string, but rather you're setting it just to the latest character. so at first, reverseIt is [], then becomes d, then becomes a, then becomes v, and so on, because at each step, it is being equaled to str[i] + testing, and because testing is always [], it literally becomes like this: reverseIt = str[i], so at the end, it only contains the last character of the string!

imans77
  • 516
  • 5
  • 16
3

The line

reverseIt = str[i] + reverseIt;

might become clearer if you think about what the temporary result of the loop body execution looks like for the for start, intermediate and end indexes:

1. Start (i = 0)

reverseIt === str[0] + reverseIt === str[0] + []

There's a subtle but important detail here in that + will silently coerce the type of [] into a string, i.e. [] will be converted to ''.

2. Intermediate (0 < i < str.length):

reverseIt === str[i] + reversetIt === str[i] + (str[i - 1] + ... + str[0] + [])

3. End (i = n - 1):

reverseIt === str[n - 1] + reversetIt === str[n - 1] + (str[n - 2] + ... + str[0] + []) === str + []

In the two lines which didn't work, you're dropping the accumulated result. So for each index

reverseIt === str[i] + [] 

respectively

reverseIt === str[i] + ''

Which means you will always end up with a string only containing the last character in the original string (or the empty string).


On a sidenote, with a combination of Array.from, and Array.reduce you can get the result in one line:

const reverse = (s) => Array.from(s).reduce((result, c) => `${c}${result}`, '');

console.log(reverse('JavaScript'));
FK82
  • 4,907
  • 4
  • 29
  • 42
2

If you didn't already know, basically a string is an array of characters it self. You can loop through a string just like you do with arrays, and with each iteration you will get a single character of that string.

function reverseString(str) {
    var data="HELLO WORLD!";  // Test string
    var reverseIt ="";  // variable to save reversed string
    for(var i=data.length-1;i>=0;i--) // start the loop from last character and run it towards the first character
    {
        reverseIt +=data[i] // append current character to reverse variable
    }
    document.write(reverseIt ); // print reverse
return reverseIt;
}
Danial Ahmed
  • 856
  • 1
  • 10
  • 26
2

Javascript converts arrays into strings, the "+" operator is described here , so I would suggest that you use an empty string for reverseIt. reverseIt = ""; The fourth line explained:

  • you concatenate the first character from the original string to this empty (for now) string, reverseIt
  • With the next iteration, reverseIt is going to contain the first character of the original string and you concatenate it with the second character from the original string.
  • Now reverseIt should look like this: str[1] + str[0].
  • The next iteration adds the third character of str to the existing reverseIt, that would look like str[2] + str[1] + str[0].
  • Notice that the character from the original string is added in front of the reverseIt string, str[i] + reverseIt, so the characters in the back of str will be the characters in front of reverseIt.
  • I hope my explanation is clear.
Tri
  • 2,722
  • 5
  • 36
  • 65
TitianaD
  • 46
  • 4