0

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.

ajinkyah
  • 113
  • 1
  • 1
  • 6

2 Answers2

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.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
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`.

Eloy Pineda
  • 2,117
  • 17
  • 22