69.6k views
5 votes
4.Write a JavaScript program to find if a given word is a palindrome or not. Word is given by user via prompt command.

User Nikolaj
by
3.1k points

1 Answer

2 votes

Answer:

Here is the JavaScript program:

function Palindrome(word) {

return word == word.toLowerCase().split("").reverse().join("") ? true : false; }

inputWord = prompt("Enter a word to check its if its palindrome or not?");

alert(Palindrome(inputWord));

Step-by-step explanation:

The function Palindrome takes a word as argument.

return word == word.toLowerCase().split("").reverse().join("") ? true : false; }

This statement first converts the word, which is a string to lower case letters using toLowerCase() method. Next split() method splits the word string into an array of strings, then reverse() method reverses the this array and join() method joins all the elements of the array back to the string. At last the conditional statement checks if the resultant string (reverse of word) is equal to the original word (that was input by user). If both the word and its reverse are equal/same then the program outputs true otherwise returns false.

inputWord = prompt("Enter a word to check its if its palindrome or not?"); statement uses prompt command to take input from the user. inputWord holds the word that user enters.

alert(Palindrome(inputWord)); statement calls Palindrome() method by passing the inputWord (word entered by user) to check if the input word is a palindrome or not. alert() method displays an alert box ( a message) with true if the inputWord is a palindrome otherwise it displays false.