ajinkyah
ajinkyah

Reputation: 111

Need explanation on following type of Javascript code

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.

Upvotes: -1

Views: 67

Answers (2)

Tomalak
Tomalak

Reputation: 338208

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.

Upvotes: 2

Eloy Pineda
Eloy Pineda

Reputation: 2187

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`.

Upvotes: 0

Related Questions