In this article, we’ll discuss creating a JavaScript program that will check whether a given string is a palindromeJavaScript program that will check whether a given string is a palindrome. A palindrome is a word, phrase, number, or another sequence of characters that reads the same forward and backward.
Introduction to Palindromes
A palindrome is a string that reads the same forward and backward. Some examples of palindromes are “A man, a plan, a canal, Panama!”, “Able was I ere I saw Elba”, and “Madam, in Eden, I’m Adam”.
To determine whether a string is a palindrome, we need to compare the first and last characters of the string, then the second and second to last characters, and so on, until we reach the middle of the string. If the characters match, then the string is a palindrome. If they don’t check, then the string is not a palindrome.
Understanding the Program
To create a JavaScript program that will check if a string is a palindrome, we’ll need to understand the following concepts:
- How to get the length of a string in JavaScript
- How to compare characters within a string
- How to loop through a string
Getting the Length of a String in JavaScript
In JavaScript, we can get the length of a string by using the .length
property. For example, the following code will get the length of the string "hello"
:
var word = "hello";
var length = word.length;
console.log(length); // Output: 5
Comparing Characters Within a String
We’ll need to use square brackets and an index number to compare characters within a string. For example, the following code will compare the first and last characters of the string "hello"
:
var word = "hello";
if (word[0] === word[word.length - 1]) {
console.log("The first and last characters are the same.");
} else {
console.log("The first and last characters are not the same.");
}
Looping Through a String
We’ll need to use a for loop to loop through a string. For example, the following code will loop through the string "hello"
and print each character on a separate line:
var word = "hello";
for (var i = 0; i < word.length; i++) {
console.log(word[i]);
}
The Final Program
Now that we have a basic understanding of how to get the length of a string, compare characters within a string, and loop through a string, we can combine these concepts to create a program that will check if a string is a palindrome:
var word = "racecar";
var isPalindrome = true;
for (var i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
console.log("The word is a palindrome.");
} else {
console.log("The word is not a palindrome.");
}
Thanks for reading. Happy coding!