javascript

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.


Solution

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