3

A function in JS can be called in the very strange way:

[1,2,3].join``
 -> "123"

Could somebody explain how it works "under the hood" or provide a link to some explanations?

Yoshi
  • 51,516
  • 13
  • 81
  • 100
  • The two backticks make it work somehow, I'm not sure what's happening. – Barmar Mar 12 '20 at 09:19
  • Oh nice, it does work! Would also like to know why – Alon Eitan Mar 12 '20 at 09:19
  • 2
    Have a look: https://stackoverflow.com/questions/35949554/invoking-a-function-without-parentheses and see example *5.* in the accepted answer – Sebastian Kaczmarek Mar 12 '20 at 09:24
  • To clarify: You shouldn't be calling "normal" functions this way. There are special functions that should be called this way. E.g. `String.raw` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw – Felix Kling Mar 12 '20 at 09:25
  • 2
    I think this is a valid question regarding the "under the hood" part. The other answers merely address what it is and how it can be used but not who it works. I'd like to know that, too. – Scheintod Mar 12 '20 at 09:35

3 Answers3

1

Tagged template literals call the function that precedes them, which in this case is join

Max
  • 3,228
  • 1
  • 8
  • 12
1

It seems you are referring tagged templates which allow you to parse template literals with a function & first argument of a tag function is related to the expression. Here join is the tag function

console.log([1,2,3].join`,`)
brk
  • 43,022
  • 4
  • 37
  • 61
-4

(Always) Check MDN web docs for enlightenment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

The join() method creates and returns a new string by concatenating all of the elements in an array (...) separated by commas or a specified separator string.

JulioSa
  • 58
  • 5