0

Here is the code I wrote on palindrome, no errors, but not working:

function palindrome(str) {
  // Good luck!
  x = 0;
  y = 0;
  for (x = 0; x == str.length; x++){ 
  str2 = str.reverse();
   for(y = 0; y == str2.length; y++){

    var firstChar = str.length[x];
    var lastChar = str2.length[y];
    if (firstChar === lastChar){
  return true;
  }
}
}
}
palindrome("eye");

I will appreciate some directions.

dareadel
  • 33
  • 5
  • 4
    *but not working* - what do you mean *not working*? *What* doesn't work? – Andrew Li Oct 19 '16 at 02:21
  • There are some good solutions out there. http://stackoverflow.com/questions/14813369/palindrome-check-in-javascript – Brian Oct 19 '16 at 02:25
  • 1
    Walk though your code line by line on a piece of paper or on a blackboard. Or, walk though your code line by line using the debugger. You should be able to find the problem in your algorithm quite easily. –  Oct 19 '16 at 04:06

1 Answers1

1

var str="eye";
var strArray=str.split("");
var revStrArray=strArray.reverse();
var revString=revStrArray.join("");
if(revString===str)
  console.log("palindrome");

you are reinventing the wheel Try to make use of the library functions

var str="eye";

str==str.split("").reverse().join("")

str.split("")->splits it into Array as "e","y","e"
str.split("").reverse()->reverse works on array and makes it as "e","y","e"
join->makes again it as string ,now this will be "eye"

You need not run a for loop for this. Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50