Basic Algorithm Scripting: Reverse a StringPassed (Completed but confused)

Hi! So after some time I was able to complete this, but for some reason I am not understanding why certain things I wrote do what they do… lol. It made sense when I wrote certain things but then I started to read it over and don’t particularly understand why it got that answer.

Why does:

newStr = finalArr[i] + newStr

give me the answer of olleh, but if I were to do

newStr = newStr + finalArr[i];

give me hello?

And If I am pushing string[i] into FinalArr, why isn’t newStr the same answer if they were both looping the same amount of times?

Sorry if this is too much or if I’m asking it in a confusing way!! Thank you!

Your code so far


function reverseString(str) {
let finalArr = [];
let newStr ="";

for(let i=0; i< str.length; i++){
 finalArr.push(str[i]);
 newStr = finalArr[i] + newStr ;
}
console.log(newStr);
return newStr;
}

reverseString("hello")

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Reverse a String

Link to the challenge:

Let’s break down your code for each iteration so that you can have a clear idea of how things are working here in every loop. And why newStr = finalArr[i] + newStr gives ‘olleh’, and newStr = newStr + finalArr[I] gives ‘hello’.

function reverseString(str) {

so you call the function and value of str = hello

let finalArr = [];
let newStr ="";

for(let i=0; i< str.length; i++){

  1st iteration
  loop started here, so i = 0, finalArr = [], newsStr = ''
  finalArr.push(str[i]);  now finalArr = [h]
  newStr = finalArr[i] + newStr ;  now newStr = 0th index of finalArr + newStr, so h+'' = h

  2nd iteration
  now i = 1, finalArr = [h], newsStr = 'h'
  finalArr.push(str[i]);  now finalArr = [h, e]
  newStr = finalArr[i] + newStr ;  now newStr = 1st index of finalArr + newStr, so e+h = 
  'eh'
  so according to your question if you do 
  newStr = newStr + finalArr[i],   h + e = he so order didn't change here.


  3rd iteration
  now i = 2, finalArr = [h, e], newsStr = 'eh'
  finalArr.push(str[i]);  now finalArr = [h, e, l]
  newStr = finalArr[i] + newStr ;  now newStr = 2nd index of finalArr + newStr, so l+eh = 
  'leh'

and so on 



}
console.log(newStr);
return newStr;
}

reverseString("hello")

Hope you got your answer and able to understand the logic :slightly_smiling_face:

1 Like

Yes this helped so much!!! Thank you for this great breakdown! :smile: