Valid Palindrome Using Every Method

Adam James
2 min readAug 28, 2021

This week, I decided to return to the Valid Palindrome challenge I wrote about a couple months ago. The solution I came up with was decently efficient, faster than about 66 percent of all passing submissions, and I wasn’t able to improve on that number, but my new solution was significantly more efficient in regards to the amount of space it used, jumping from the 30th percentile all the way up to 98 percent. The main reason I decided to adjust my answer was because it gave me the opportunity to experiment with something I don’t have as much experience with as I would have liked, JavaScript’s every method.

In this new solution, I began with saving the same string variable that I used in my previous solution, but I chained an additional method, the split method, onto the end to split the string into an array, since every is an array method. This variable is used as the returned value while using the every method in the same line.

Completed Function Using Every

The every method takes in a function as its first argument. This function is used as a test for every element in the array that the method is stringed onto, if every element passes the test, then the method returns true, but if even a single element fails the test, the method returns false. Since this coding challenge’s instructions tell you to check if the string is the same when it’s reversed, the every method can be used to check if the last element is the same as the first, then if the second-to-last is the same as the second, and so on.

In the callback function used inside every, the first argument is the element of the array that’s currently being used in the every loop. In this specific instance of the method, I want to use the second argument in the callback function, which will allow me to access the index while inside of the function body. I want to check if each character is equal to the element on the opposite side of the string. To find the element at the end, I can use string.length — 1 to get the end, then use the index of each character being checked to move that end character one element closer to the front as the method runs.

--

--