JavaScript Algorithms Part 1: PALINDROME

Seun Faluyi
2 min readMar 25, 2019
Image Credits: Zooglobble

Welcome to the part 1 series of JavaScript Algorithms. I’m so glad to be doing this and I’m pretty sure you’re in for an amazing ride.

All solution and test code for my JavaScript Algorithm Challenge can be found here:
https://github.com/seunzone/js-algorithms

The Palindrome question is a very popular algorithm question asked during interviews and it is probably one of the first challenges you’d have to deal with when you start out as a programmer, I'd be sharing my thought process on solving this question.

Question:
A palindrome is a string that reads the same forward and backwards, for example, radar, toot, and madam. Write a JavaScript Algorithm that checks if a string is a palindrome or not.

Let’s do this, I’d start out by creating a function where we’d write our solution:

const palindrome = str => {    
// solution goes here
}

The above function will hold our solution, the str attribute would hold the string we are trying to test for.
Since a Palindrome is a word that returns the same value when it is reversed, I’d start out by turning the string the user enters into an array by calling the .split('') method. This method will return an array of each element of the string.

str = 'come'
var myWord = str.split('');
console.log(myWord)
OUTPUT: ["c", "o", "m", "e"]

The next thing I’d do is to call the .reverse() method, this would reverse the string.

str = 'come'
var myWord = str.split('').reverse();
console.log(myWord)
OUTPUT: ["e", "m", "o", "c"]

Then we’ll convert the array we now have back to a string by calling the .join('')method.

str = 'seun'
var myWord = str.split('').reverse().join('');
console.log(myWord)
OUTPUT: "emoc"

Now we’ve been able to successfully reverse a string 😀, next we’ll check compare our new variable to the initial variable. It the initial variable (str) is the same as our new variable (myWord) then the string is a palindrome and if otherwise, it is not a palindrome.

Final Solution:

const palindrome = str => {
const myWord = str.split('').reverse().join('');
if (myWord === str){
return true
}
else {
return false
}
}

Now Write your own solution (Assumes you have node installed):
1. Clone https://github.com/seunzone/js-algorithms
2. Install the dependencies yarn install
3. Test your code in the terminal using yarn run palindrome

Feel free to post your solutions in the comment section, I’d like to learn from other approaches, thanks for reading.

--

--