Billy Billy - 4 months ago 41
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.


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

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


var str= 'blue';





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?


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--).