There are a couple problems with this code, although you're on the right track. First, your usage of toString
is slightly wrong:
toString(101); // '[object Undefined]'
toString
should be called as a method of x
, like x.toString()
. See this page for more details. If you change it to x.toString()
, it works:
var x = 101; // "101"
Second, you are currently comparing arrays with ==
, which won't do what you want. Notice that:
[0, 1] == [0, 1] // false
whereas
"01" == "01" // true
This is because JS compares strings by value, but doesn't compare objects (which includes arrays) by value. For example:
var x = 1;
var y = 1;
console.log(x == y); // true
var a = [1];
var b = [1];
console.log(a == b); // false
console.log(a == a); // true
To learn more about this, read this question or try googling for 'javascript pass by reference'. But in brief, one solution to your problem would be to just use strings, which work as you would expect with ==
.
After fixing these problems, your code should look like this:
var isPalindrome = function(x) {
var convertToString= String(x);
var reversedString= convertToString.split("").reverse().join("");
if(x<0){
return false;
}
if(convertToString == reversedString){
return true;
} else {
return false;
}
};
You could also consider shortening the if statement at the end and making the spacing more consistent:
var isPalindrome = function(x) {
var convertToString = String(x);
var reversedString = convertToString.split("").reverse().join("");
if(x < 0){
return false;
}
return convertToString == reversedString;
};