Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Palindromes

Exercise 7 Easy

Prerequisites for the exercise

  1. JavaScript Control Flow
  2. JavaScript Data Types
  3. All previous chapters

Objective

Create a program that asks the user to enter a word, and determines whether it is a palindrome or not.

Description

A palindrome is a word that reads the same forwards and backwards.

For example, 'ada' is a palindrome. If you read it forwards, it's 'ada'; and similarly, if you read it backwards, it's still 'ada'. Since it's same in both directions, it's a palindrome.

Now, consider the word 'bulb'. Forwards, it's read as 'bulb'. But backwards, it's read as 'blub'. Since both these directions yield different words, 'bulb' is not a palindrome.

By this means, every single letter is a palindrome as well. 'a' is a palindrome, 'b' is a palindrome, and so on and so forth.

In this exercise, you have to create a program that asks the user to enter a word, and then outputs backs 'Yes' if it is a palindrome, or otherwise 'No'.

You must create a function for this exercise.

The input prompt asking for the word shall display the text 'Enter a word:'.

If the entered word is a palindrome, output the following:

Yes, '<word>' is a palindrome.

However, if the entered word is not a palindrome, output the following:

No, '<word>' is not a palindrome.

In both these snippets, <word> is the word entered by the user.

Shown below are an example:

Live Example

Hints

Hint 1

Use a for loop to iterate as far as almost half the length of the string.

Hint 2

Using the for loop, iterate up to word.length / 2.

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-7-Palindromes and put the .html solution files for this exercise within it.

Solution

The function that we'll create for this exercise will determine whether a given word is a palindrome or not. It will take in a string value and output true if it is a palindrome, or otherwise false. Based on the return value of this function, we could then make the desired output.

First, let's get settled on the naming for the function.

We'll call the function isPalindrome(), since it checks whether a string 'is a palindrome', or not. The argument it'll take (which is a string) could simply be called word.

Here's the function's initial setup:

function isPalindrome(word) {
    // code goes here
}
Usually, functions that return Booleans are named starting from 'is', since the word 'is' implies a question.

With the naming out of the way, next let's think on the logic of the function.

The idea is that we need to go upto half the length of the string and compare each character from the left with the corresponding character from the right.

If in any comparison, we find out that the characters being compared are not the same, we could immediately say that the given string is not a palindrome i.e. return false. If such a case never arises, we could return true in the end.

Which concept in JavaScript does this, as a whole, remind of?

We need to iterate upto half the length of the string, likewise we need to use a loop to accomplish this.

But which loop to use: for or while?

Technically, we could use any of these. But for now, we'll go with for because setting it up is easier compared to while.

Recall that the for loop is handy when iterating over a given sequence. In this case, the sequence is the string word.

But how do we know how far to iterate in this problem?

Well, we need to go upto half the length of the string so let's try the code below:

function isPalindrome(word) {
    for (var i = 0; i < word.length / 2; i++) {
        // code here
    }
}

Let's quickly do a bit of thought work to see whether i < word.length / 2 actually leads to the correct number of iterations.

If we have a string with an even number of characters, we need to go as far as half of its length. For example, given the string 'deed', its length is 4 which is even, hence we ought to go as far as the second (4 / 2 = 2) character in the string.

Why not consider a few strings and see whether word.length / 2 takes us as far as is required:

  1. In a string of length 2 — such as 'aa' — we need to do 1 comparison, and word.length / 2 is 1, which would lead to 1 iteration.
  2. In a string of length 4 — such as 'deed' — we need to do 2 comparisons, and word.length / 2 is 2, which would lead to 2 iterations.
  3. In a string of length 6 — such as 'denned' — we need to do 3 comparisons, and word.length / 2 is 3, which would lead to 3 iterations.

Perfect!

Let's now think about odd-length strings.

Let's first see exactly how far do we need to go in an odd-length string.

Suppose we have the string 'ada'. It turns out that we need to go only as far as the first character to determine whether 'ada' is a palindrome or not. If the highlighted parts in 'ada' are the same, the string is a palindrome.

There is no need to compare the letter 'd'. The middle character in an odd-length string would anyways be compared against itself, hence it's better to skip this step.

As before, we'll consider a few strings and see whether word.length / 2 takes us as far as is required:

  1. In a string of length 3 — such as 'ada' — we need to do 1 comparison, and word.length / 2 is 1.5, which would lead to 1 iteration.
  2. In a string of length 5 — such as 'dioid' — we need to do 2 comparisons, and word.length / 2 is 2.5, which would lead to 2 iterations.
  3. In a string of length 7 — such as 'racecar' — we need to do 3 comparisons, and word.length / 2 is 3.5, which would lead to 3 iterations.

Perfect! The word.length / 2 expression works just as desired.

So, to summarise, the for loop iterates from i = 0 to i < word.length / 2.

Consider the code below:

function isPalindrome(word) {
    for (var i = 0; i < word.length / 2; i++) {
        if (word[i] !== word[word.length - i - 1]) return false;
    }
    return true;
}

Inside the loop, we compare word[i] with the corresponding character from the end of the string. This character from the string's end is at the index word.length - i - 1.

In the comparison, if the characters are not the same, it means that the string is definitely not a palindrome; hence, we return false (without completing the loop).

However, when the string is actually a palindrome, this conditional never gets executed, which means that the loop goes to completion. At this point, the statement following the loop is executed. Likewise, we return true here to say that the string is a palindrome.

With the function is_palindrome() created, we now just need to call it on the value input by the user, and make the desired output.

function isPalindrome(word) {
    for (var i = 0; i < word.length / 2; i++) {
        if (word[i] !== word[word.length - i - 1]) return false;
    }
    return true;
}

var word = prompt('Enter a word:');
if (isPalindrome(word)) {
    document.write("Yes, '" + word + "' is a palindrome.");
}
else {
    document.write("No, '" + word + "' is not a palindrome.");
}

This completes our exercise.

Benefits of using a function

In the exercise above, we could've used a for loop directly to solve the task without having to encapsulate it inside a function. So then why did we use a function?

Well, a function has a couple of advantages.

  1. Firstly, we could reuse it in any other place where we ought to perform a palindrome check.
  2. Secondly, with a function, we could perform as many palindrome checks as we want to, without having to rewrite the logic of the check.
  3. Compared to implementing this solution directly in a loop (without encapsulating it inside a function), it's easier to implement a palindrome check using a function.