A more sophisticated solution can be found by utilizing the every()
function which is accessible through the MDN Web Docs
Your approach of splitting the string into an array is on the right path because array helper methods like every()
or map()
cannot be used directly on strings, only arrays. You may want to consider this:
function palindrome(str) {
str.split('')
}
Then, you can utilize every()
with it in this way:
function palindrome(str) {
str.split('').every()
}
Why use every()
?
This function will iterate over each element in the array. It takes a fat arrow function as its first argument like this:
function palindrome(str) {
str.split('').every(() => {
});
}
The arrow function will have a second parameter char
, representing each element in the array:
function palindrome(str) {
str.split('').every((char, ) => {
});
}
In order to compare each element with its mirrored counterpart, how do we access the elements on the other side?
Luckily, the second argument provided to this function is the index of the element, saved as i
:
function palindrome(str) {
str.split(‘’).every((char, i) => {
});
}
When this inner function is first called, i
will equal zero.
Within this every function, I can perform my comparison between the current element and its mirror image on the opposite end of the array.
Gaining access to the other side can be tricky.
Initially, when the function runs, it's at index zero.
So with i = 0
, to reach the element on the other end, we need to look at the entire array and select the element at position length
of the array - 1
.
Remember, JavaScript arrays are zero-indexed.
Why subtract 1? This accounts for the fact that there is more than one element in the array. Instead of looking at the elements as .length
, we must reference them using .length - 1
like so:
function palindrome(str) {
str.split(‘’).every((char, i) => {
return char === str[str.length - i - 1];
});
}
Subtracting 1 ensures we correct for zero-based indexing within JavaScript arrays.
Lastly, remember to return the result of the every() method call like this:
function palindrome(str) {
return str.split(‘’).every((char, i) => {
return char === str[str.length - i - 1];
});
}