SeaWarrior404
SeaWarrior404

Reputation: 4167

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

Upvotes: 1

Views: 101

Answers (2)

bmceldowney
bmceldowney

Reputation: 2305

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.

Upvotes: 2

xwcg
xwcg

Reputation: 196

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.

Upvotes: 0

Related Questions