Palindrome & JS

Pedro Loureiro
3 min readJun 25, 2019

--

What is a Palindrome?

A palindrome is a word, phrase, number, or even the conjunction of both words and numbers, that has the particularity of being read the same backwards and forward.

Let’s give a bit of history

Palindromes date back to 70AD when they were found in a graffito (informal inscription) in an ancient city called Herculaneum which was destroyed due to a volcanic eruption of Monte Vesuvius.

A fun fact

“saippuakivikauppias”, have you ever heard about it?

It is a Finish word that holds the World Guinness Record for the longest known palindrome in any language.

What is a saippuakivikauppias anyway?

Is a travelling salesman who sells caustic soda to the soap industry.

You might be bored with history by now…

Well…Before jumping into the text editor and write our code, let’s think about the characteristics of a palindrome.

Let’s take this example: “level”. This word has 5 letters, right? The letter ‘v’ happens to be in the middle of this word, so it does not play any significant part to check whether ‘level’ is a palindrome or not. A palindrome is simply a symmetric word. So just like any symmetric figure the left side will be exactly the same to the right side.

Photo by Vitor Pinto on Unsplash

Iterating through ‘level’ from both sides would be a good idea to check whether it is a palindrome.

Code

Note: There are different ways of solving the Palindrome. In this one I’ve used a for loop but it could also be done by reverting the original string and store it in a variable and checking if they are equal to each other.

Let’s examine this code line by line…

Firstly we create an arrow function that takes a string as a parameter.

As we want to check both sides of the given string, we need to get its length and divide it by 2 and store it in a variable called stringlength.

That’s what we do in line 2, but we use a special class method called .floor that returns the nearest integer in downward direction. We need this method because we want to check the string equally from both sides.

On line 3 we set our string to lower case so we don’t run in any problems.

Then, we iterate through our string until i is 1 value less that stringlength.

Through that iteration process we are continuously checking if the string at position[i] is different than the string at position[string.length-1-i]. If at any point the characters are different, then we return false for palindrome and return true if false has not occurred.

Let’s test our level word by using console log and calling the function.

We’ve just proven that level is a palindrome.

--

--