What does .join`` mean in JavaScript?

arr.join``; is a tagged template literal.

It applies join (or any other function) to "the content of the template literal string".

When I say "applies to the content of the template literal string" it is actually a little bit more complicated than that: all static parts of the string are put into an array as the first argument and the interpolated values as the remaining arguments.

A simple example will make it easier to understand:

var demo = (str, ...names) => {
  console.log(str);
  console.log(names);
};

var users = ['john', 'jane', 'joe'];

demo`Members: ${users[0]}, ${users[1]} and ${users[2]}.`;
// LOG: ["Members: ", ", ", " and ", "."]
// LOG: ["john", "jane", "joe"]

demo``;
// LOG: [""]
// LOG: []

The last line answers your question because arr.join``; is the same as arr.join(""); just two characters shorter which is useful when you compete in JS1K for example.

In this particular case I'm not sure that the author wanted to save a few bytes because we can shorten the initial statement as follow:

new Array(10).fill('1').join``;
new Array(10).fill(1).join``;
Array(10).fill(1).join``;
'1'.repeat(10);
'1111111111';

Is a tagged template just a glorified function call?

These two expressions may look similar but they are not:

var yy = 20;
year`19${yy}`;
year(`19${yy}`);

In the first expression we have access to the static and dynamic parts of the string: "19" and 20. In the second expression we only get the "final" string "1920".

This is useful when one wants to preserve intent yet allow complex text processing behind the scene.

We know that this is unsafe:

var sql = `SELECT * FROM users where email="${email}" AND password="${password}"`;

To mitigate the risk of SQL injection, it is not uncommon to see things like:

var sql = select('*').from('users').where('AND').eq('email', email).eq('password', password);

However it could be argued that we have traded the expressiveness of SQL with a somewhat awkward API that people are less likely to be familiar with.

If a tagged template literal has access to both static and dynamic parts of a string we can build domain-specific tagged template literals:

var sql = safe_sql`SELECT * FROM users where email="${email}" AND password="${password}"`;

What you're seeing is a tagged template literal, part of the ES6 specification. That pattern is heavily used in e.g. Google's Polymer Project (now lit-element). It invokes the supplied function (or in this case method) with the supplied template literal.

In addition to being used to create a Domain-Specific Language (DSL) of sorts, it's also frequently used to reduce the byte count for Javascript answers in code golf In the case of the Google project I linked, it's used as part of a domain-specific HTML templating language.

Tags:

Javascript