Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Write a function to check whether a given string is a palindrome.

Write a function to check whether a given string is a palindrome.Note: A palindrome is a word that is the same when read backwards. e.g. kayak, madam

1 Answer

Given that you know about strings and that each characters in a string can be accessed by its index, you should be able to come up with a solution by yourself. Use for loop to come up with a solution.

var candidatePalindrome =  prompt("Enter a word: ");
var n = candidatePalindrome.length - 1 ;

var isPalindrome = 1;
for (var i = 0; i <= n; i++) { 
  if (i < n-i && candidatePalindrome[i] !== candidatePalindrome[n-i]){
      isPalindrome = 0;
      break;
  }
}

if (isPalindrome){
   console.log("It is a Palindrome");
}else{
   console.log("It is not a Palindrome");
}

This problem can also be addressed with recursion. Can you think of a way?