Please check out this code and help me understand what went wrong

This is 2nd exercise from Basic Algorithm Scripting - Reverse a string. Below is my approach to solve the problem.

function reverseString(str) {
  let arr = [];
  str = str.split("");
  for(let i = 0; i < str.length; i++) {
    a.push(str.pop());
  }
  str = a.join("")
  return str;
}

reverseString("hello");

Unfortunately, it is not working. But, if I do this it is working

function reverseString(str) {

  let a = [];

  str = str.split("");

  let b = str.length;

  for(let i = 0; i < b; i++) {

    a.push(str.pop());

  }

  str = a.join("")

  return str;

}

reverseString("hello");

Someone please explain me what’s happening. I mean why is it not working when I am using i < str.length but when I assign the same to a variable and use that variable instead of actual value its working. What am I missing?

The method .pop() modifies the array. It removes an item from the popped array. That means that the length of the array changes and that the indices of the array elements change.

3 Likes

Thanks a ton for the fast reply. Now it makes sense.

I’m glad I could help. Happy coding!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.