the function returns 'Hello, world!' it's very confusing to understand trim and bind inside an array as string.
f=''['trim']['bind']`Hello, world!`()
the function returns 'Hello, world!' it's very confusing to understand trim and bind inside an array as string.
f=''['trim']['bind']`Hello, world!`()
I hadn't seen something like this before. I found it very interesting so looked into how it works. Here's my attempt to explain:
''['trim']
-- The initial blank string ''
has string methods like .trim()
available to it. Using the bracket notation you can access the trim method with ''['trim']
.
''['trim']['bind']
-- Rather than calling the trim method though (which would require adding () to the end), we call the .bind()
method that is part of the prototype of trim, again using bracket notation. Bind takes its initial argument and binds it to the previous function (trim) as the 'this' keyword.
''['trim']['bind']`Hello, world!`
-- The final piece here is passing the string 'Hello, world!'
inside an array to the .bind()
method. The notation here is a string literal being used as a tagged template. This allows a template literal to be used as an array argument to its preceding "tag", in this case the bound function. This is now equivalent to ['Hello, world!'].trim(). Trim coerces an array of strings to a string with each element separated by a comma. But as there is only 1 element, that single element is returned.
f=''['trim']['bind']`Hello, world!`()
-- Calling the whole thing with () at the end results in trimming 'Hello, world!', which just returns the same string as there is nothing to actually trim. It was all just a ruse to get to the string method's prototype!