-1

I use codefights and one of the solutions for finding if a string is palindrome or not is as follows:

PalindromeOrNot = s =>
s == [...s].reverse().join`` ? `Yes` : `No`

Here PalindromeOrNot is the function name and s is a parameter. I understand that the second line directly returns Yes or No but there is no return keyword used. Also, I have never seen such code anywhere else in Javascript. Can someone please explain.

1
  • Which part do you need explained? Commented Nov 21, 2024 at 8:06

2 Answers 2

2

Let's deconstruct this:

PalindromeOrNot =    // an assignment
s => stmt            // arrow notation, shorthand(*) for function (s) { return stmt; }
s ==                 // ...where "stmt" is: a comparison
[...s]               // array destructuring (turns s into an array of characters)
.reverse().join``    // reverse the array, join with the empty string
?                    // ternary operator (after the comparison)
`Yes` : `No`         // results of the ternary, either 'Yes' or 'No',
                     // depending on whether the string equals its reverse

So in other words, this is a fancy way of writing

PalindromeOrNot = function (s) {
    return s == s.split('').reverse().join('') ? 'Yes' : 'No';
}

On .join`` read this question: Backticks calling a function


(*) Almost. There is a difference between the regular functions and array functions when it comes to the handling of this.

Sign up to request clarification or add additional context in comments.

Comments

0

It will be equivalent to this function:

PalindromeOrNot = function (s) {
  return s == s.split('').reverse().join('') ? 'Yes' : 'No';
}

It just have some ES2015 sugar syntax like arrow functions (params) => expression, spread operator [...variable] and template literals `string text`.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.