Last updated on March 4, 2020
This time, I thought of writing a small logic or algorithmic kind of question that we can solve by using JavaScript. Here we will see How to do Palindrome with JavaScript.
Introduction
At least once in a while, we have faced this kind of question during our job-interview. Yes, how to validate given input is Palindrome or not with JavaScript.
I believe every problem will have multiple ways to solve likewise here I represent my own solution to this logic but with ES6 style.
Palindrome with JavaScript
function getPalindrome(input = '') {
if(!input) {
return;
}
const newValue = input.toString().split('').reverse().join('');
return input === newValue;
}
The function named getPalindrome
accepts input text as the parameter but here acting as the default parameter. We will handle even if the user doesn’t pass the value will simply reject it.
By using split, reverse and join
prototype utility methods we would be able to achieve this logic. reverse
prototype method is derived from an array value.
Just writing this simple logic, we used two simple and most important things as a best-practice way of writing JavaScript code.
Early return, this will help to improve our code performance. We will always keep this in mind, whatever we write first will check the negative possible case to catch and return back. Eventually no need for using if-else
code block.
In this written function, did you notice one thing? YAH!!! Method Chaining. This simple thing makes our code more readable thus reduces lines of code.