1

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

SeaWarrior404
  • 3,811
  • 14
  • 43
  • 65
  • isn't it obvious? :p throw the code in babel transpiler to see the ES5 version of events :p – Jaromanda X May 30 '17 at 23:03
  • 1
    *"find the fastest way"* – well it may be a succinct (ie clever) implementation but iterating over the input 3 times is certainly not going to be the *fastest* way. – Mulan May 30 '17 at 23:13
  • Upon review of the answers, the one you've selected here is one of the slowest, btw. It's at least 20 times slower than [fastestIsPalindrome](https://stackoverflow.com/a/25091111/633183) provided by Jason Sebring. This is a perfect example of what goes wrong when you try to make code too clever – Mulan May 31 '17 at 00:31

2 Answers2

2

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.

bmceldowney
  • 2,307
  • 13
  • 19
0

JS interprets it as the first argument for the join function, as otherwise it would join the string with the default ",". The part ".join``" equates to ".join('')", without having to add the two extra chars for the parentheses.

As to why exactly only `` works for this and not "" or '', you would have to look up the ECMA Script documentation; I don't have an explanation offhand for you.

xwcg
  • 196
  • 9