Search code examples
javascriptpalindrome

How does this line of code for checking whether a word is palindrome or not, work in JS?


So I was going through solutions to find the fastest way to perform the operation of checking whether a word is palindrome or not in Javascript. I came across this as one of the solutions listed and it works, but I have no clue why the `` is used and how exactly it works. A detailed explanation would be welcome.

The code is as follows,

p=s=>s==[...s].reverse().join``
p('racecar'); //true

The link for the original answer is, https://stackoverflow.com/a/35789680/5898523


Solution

  • tagged template literals: without tagged template literals the sample would look like this:

    p = s=>s==[...s].reverse().join('')
    

    EDIT:

    Looks like I answered before I read your question in full, sorry. Template literals allow for placeholders that look like ${placeholder}. ES6 runs the template through a built-in processor function to handle the placeholders, but you use your own custom function instead by using this 'tag' syntax:

    tagFunction`literal ${placeholder} template`
    

    The example code uses (abuses in my opinion) this functionality to save 2 characters by invoking the join method as a tag with an empty template.