Billy Billy - 1 month ago 9
Javascript Question

Javascript - Undefined array value after string .split

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?

Answer

The reason you are getting the result you have is because the first iteration, i equals split.length, which is a bigger number than the largest index in the array, so split[i] returns undefined.. Try for(var i=split.length-1; i>=0; i--).

Comments