0

I wanted to check if a string is palindrome, but I have a problem in reversing a string. I know there's a lot of Questions about palindrome in Javascript, but i want to find it on my way and I still can't find the solution on those Questions.

Code

function reverse(string){
  var str = string;
  var split = str.split("");
  var newStr= "";

  for(var i=split.length; i>=0; i--){
     newStr += split[i];
  }

  console.log(newStr); 
}

var str= 'blue';

reverse(str);

Results

"undefinedeulb"

Question

As we can see, the results was an undefined value at the start of the string. I tested this code with PHP script, and It works fine. How could this be a problem with Javascript? and How to get rid of it?

4
  • 3
    str.split("").reverse().join("") reverses a string Commented Oct 19, 2016 at 22:16
  • 1
    You are trying to access split[split.length] which is undefined. You are off by one Commented Oct 19, 2016 at 22:18
  • FYI, the reason why it seems to work in PHP is that the undefined index seems to be coerced to an empty string somehow. It's still wrong though. Commented Oct 19, 2016 at 22:45
  • Exactly Felix! Thanks guys :) Commented Oct 19, 2016 at 23:11

2 Answers 2

1

The index of an array starts with 0, for example in

var arr = ["a", "b", "c", "d", "e"];

the last one is arr[4] // "e"

but arr.length is 5, so arr[5] is undefined.

So arr[arr.length] is always undefined!

In your example the first iteration, i equals split.length is undefined, therefore try

for(var i = split.length - 1; i >= 0; i--).

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

2 Comments

Alternatively: for(var i=split.length; i--;) {}
That's true, and I also agree with adeneo's comment that there is a much simpler way to implement this functionality, but since Billy wanted to figure it out themselves I figured I'd leave it as close to their implementation as possible
0

split.length is equal to 4, but because arrays are zero-indexed you need to start at 3 and move down to zero.

function reverse(string){
  var str = string;
  var split = str.split("");
  var newStr= "";

  for(var i = split.length -1; i >= 0; i--){
     newStr += split[i]; console.log(i);
  }

  console.log(newStr); 
}

var str= 'blue';

reverse(str);

1 Comment

Exactly! Thanks Jeremy S

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.