I am trying to wrap my head around the concept here. It seems like the phrase
will pass a part of an array, in this case eve
, to the phrase.palindrome
method. This method will then process it. First, the var len
takes the length of eve
and subtracts 1 from it using length -1.
. As a result, var len
is assigned the number 2, since the length of "eve" is 3. Next, the for
loop iterates with var i = 0; i <= len/2; i++
.
This translates to var i = 0;
;0 <= 1; i++
. Is this interpretation correct?
I'm having trouble grasping the logic behind this block:
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
Here is the complete code snippet:
String.prototype.palindrome = function() {
var len = this.length-1;
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
}
}
return true;
};
var phrases = ["eve", "kayak", "mom", "wow", "Not a palindrome"];
for (var i = 0; i < phrases.length; i++) {
var phrase = phrases[i];
if (phrase.palindrome()) {
console.log("'"+ phrase + "' is a palindrome");
} else {
console.log("'"+ phrase + "' is NOT a palindrome");
}
}